java中前端JS公钥加密,后台私钥解密
程序员文章站
2022-04-14 18:58:25
思路:前端利用 jsencrypt.js 将用户名密码加密. 后台解密账户密码. 提供一个js连接:https://passport.cnblogs.com/scripts/jsencrypt.min.js 提供一个密钥生成连接:http://web.chacuo.net/netrsakeypair ......
思路:前端利用 jsencrypt.js 将用户名密码加密. 后台解密账户密码.
提供一个js连接:
提供一个密钥生成连接:
这里只对密码加密
效果图
2.
3.
----------------------------------------------------------------html---------------------------------------------------------------
<form method="post" action="/home/testform" onsubmit="check()">
<table>
<tr>
<td>账号</td>
<td>
<input type="text" name="username" ></input>
</td>
</tr>
</tr>
<td>密码</td>
<td>
<input type="password" id="t_password"></input>
<input style="display:none;" type="password" id="password" name="password"></input>
</td>
</tr>
<tr>
<td>
<input type="submit" value="登陆">
</td>
</tr>
</table>
</form>
<script type="text/javascript">
//公钥 这里不建议写死, 可以放在配置文件中 有后台传递过来
var publickey ="migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdnmxed+6wb6tfuqg9xvopnjom/1cap6t9jq9ajdkerrdkynkvnm0f+e+gzhklblz5g2d7ozzz4zxk5tlwywrneoprajj4ycixwp5t4dydc8zu5ra7lnmbzk7t54p1wygpwdmzji5rhqca1atnvt6ho/c4wbnep0xvr20vzgdh8nqidaqab";
function encryptpwd(val){
var encrypt = new jsencrypt();
encrypt.setpublickey(publickey);
// 加密
return encrypt.encrypt(val);
}
function check(){
var username = $("#t_username").val();
var password = $("#t_password").val();
if($.trim(username).length > 0 && $.trim(username).length < 100){
$("#username").val($.trim(username));
}
if($.trim(password).length > 0 && $.trim(password).length < 100){
$("#password").val(encryptpwd($.trim(password)));
}
return true;
}
</script>
------------------------------------------------------------------------------------java--------------------------------------------------------------------------------------------
/**
* 登陆加密测试
* @param model
* @return
*/
@requestmapping("testform")
public string testform(model model, httpservletrequest request){
string password = request.getparameter("password");
string privatekey ="miicdqibadanbgkqhkig9w0baqefaascal8wggjbageaaogbam2bf4p7pyhpn9sob3g8480k4z/vxo/pp0ld0akmosteorg0q82br/574bmcotuvnkbz3s7nnphngtloxdjaud6g9foknjjylfanm3gnh1zzo7mtruwcxtkru3ninvbka/b0xkmlmufaidubodvpqgj8ljbs0q/tg9hbs/ob0fydagmbaaecgyb7z1xs4qww7/crk9ln2i6eb1raco4v/dh+4foxyshfptpje+goe2a/rs0feu+iiigodsxtk/ff4+nw0mzndqrnj4n0zscouxk/8bf9qwltgf6/p/quia9p+qgaan5ttyvflbnlngepaz6und2deqsbl6vxiwbwhwbfnphtgjuigqjbapz4fl1qkuhi23ikhsney5ahfvk2dbiv+ywjissqr/3rpogd8de+dzvjox0xjzirdcrvbpiuejrqhzakegof7x0cqqdvjnxhdaa8xybnkgg1puraufgymcxjlcbin1kk+09pspv4+ky7bvj3vnf0yrdembvrjvc8eqvoklvtwqzh2fwhakahpfc/h5iivue6llz8f27yqf+t6u9xojnvhqwb4hdwnqr8tmdkog7v3ascoh9ub1c9krfp6rtxgbygsv9ma9fxakbjfhbtf9cu2+xodkfkskcy9vhdsru0jg0bqwrrsgb1odpmywedlbha1umqmo47zsfpeabhlo3i3gq8kf25kbfhakbd0kcdyljevomntz8kosicbadajb30k5akaxbcurbt8hwysgbc8yigewluryvkood5k5yvu5vjvduyr2j82rtm";
try {
if (!password.equals("")) {
password = com.jesims.common.utils.rsautils.decryptbyprivatekey(password, privatekey);
}
} catch (exception e) {
}
return "home/homelist";
}
-----------------------------------------------------utils------------------------------------------
import java.io.bytearrayoutputstream;
import java.security.key;
import java.security.keyfactory;
import java.security.keypair;
import java.security.keypairgenerator;
import java.security.interfaces.rsaprivatekey;
import java.security.interfaces.rsapublickey;
import java.security.spec.pkcs8encodedkeyspec;
import java.security.spec.x509encodedkeyspec;
import java.util.hashmap;
import java.util.map;
import javax.crypto.cipher;
import com.email.home.utils.base64utils;
import org.apache.commons.lang.stringutils;
/** */
/**
* <p>
* rsa公钥/私钥/签名工具包
* </p>
* <p>
* 罗纳德·李维斯特(ron [r]ivest)、阿迪·萨莫尔(adi [s]hamir)和伦纳德·阿德曼(leonard [a]dleman)
* </p>
* <p>
* 字符串格式的密钥在未在特殊说明情况下都为base64编码格式<br/>
* 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/>
* 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全
* </p>
*
* @author icewee, max.lee
* @date 2012-4-26
* @version 1.0
*/
public class rsautils {
/**
* 加密算法rsa
*/
// public static final string key_algorithm = "rsa/ecb/pkcs1padding";
public static final string key_algorithm = "rsa";
/**
* 签名算法
*/
public static final string signature_algorithm = "md5withrsa";
/**
* 获取公钥的key
*/
private static final string public_key = "rsapublickey";
/**
* 获取私钥的key
*/
private static final string private_key = "rsaprivatekey";
/**
* rsa最大加密明文大小
*/
private static final int max_encrypt_block = 117;
/**
* rsa最大解密密文大小
*/
private static final int max_decrypt_block = 128;
/**
* <p>
* 生成密钥对(公钥和私钥)
* </p>
*
* @return
* @throws exception
*/
public static map<string, object> genkeypair() throws exception {
keypairgenerator keypairgen = keypairgenerator.getinstance(key_algorithm);
keypairgen.initialize(512);
keypair keypair = keypairgen.generatekeypair();
rsapublickey publickey = (rsapublickey) keypair.getpublic();
rsaprivatekey privatekey = (rsaprivatekey) keypair.getprivate();
map<string, object> keymap = new hashmap<string, object>(2);
keymap.put(public_key, publickey);
keymap.put(private_key, privatekey);
return keymap;
}
/**
* <p>
* 用私钥对信息生成数字签名
* </p>
*
* @param data
* 已加密数据
* @param privatekey
* 私钥(base64编码)
*
* @return
* @throws exception
*/
// public static string sign(byte[] data, string privatekey) throws exception {
// byte[] keybytes = base64utils.decode(privatekey);
// pkcs8encodedkeyspec pkcs8keyspec = new pkcs8encodedkeyspec(keybytes);
// keyfactory keyfactory = keyfactory.getinstance(key_algorithm);
// privatekey privatek = keyfactory.generateprivate(pkcs8keyspec);
// signature signature = signature.getinstance(signature_algorithm);
// signature.initsign(privatek);
// signature.update(data);
// return base64utils.encode(signature.sign());
// }
/**
* <p>
* 校验数字签名
* </p>
*
* @param data
* 已加密数据
* @param publickey
* 公钥(base64编码)
* @param sign
* 数字签名
*
* @return
* @throws exception
*
*/
// public static boolean verify(byte[] data, string publickey, string sign) throws exception {
// byte[] keybytes = base64utils.decode(publickey);
// x509encodedkeyspec keyspec = new x509encodedkeyspec(keybytes);
// keyfactory keyfactory = keyfactory.getinstance(key_algorithm);
// publickey publick = keyfactory.generatepublic(keyspec);
// signature signature = signature.getinstance(signature_algorithm);
// signature.initverify(publick);
// signature.update(data);
// return signature.verify(base64utils.decode(sign));
// }
/**
* <p>
* 私钥解密
* </p>
*
* @param encrypteddata
* 已加密数据
* @param privatekey
* 私钥(base64编码)
* @return 解密数据
* @throws exception
*/
public static string decryptbyprivatekey(string encrypteddatastr, string privatekey) throws exception {
byte[] encrypteddata = base64utils.decode(encrypteddatastr);
byte[] decodeddata = decryptbyprivatekey(encrypteddata, privatekey);
return new string(decodeddata, "utf-8");
}
/**
* <p>
* 私钥解密
* </p>
*
* @param encrypteddata
* 已加密数据
* @param privatekey
* 私钥(base64编码)
* @return
* @throws exception
*/
public static byte[] decryptbyprivatekey(byte[] encrypteddata, string privatekey) throws exception {
byte[] keybytes = base64utils.decode(privatekey);
pkcs8encodedkeyspec pkcs8keyspec = new pkcs8encodedkeyspec(keybytes);
keyfactory keyfactory = keyfactory.getinstance(key_algorithm);
key privatek = keyfactory.generateprivate(pkcs8keyspec);
cipher cipher = cipher.getinstance(keyfactory.getalgorithm());
cipher.init(cipher.decrypt_mode, privatek);
int inputlen = encrypteddata.length;
bytearrayoutputstream out = new bytearrayoutputstream();
int offset = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputlen - offset > 0) {
if (inputlen - offset > max_decrypt_block) {
cache = cipher.dofinal(encrypteddata, offset, max_decrypt_block);
} else {
cache = cipher.dofinal(encrypteddata, offset, inputlen - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * max_decrypt_block;
}
byte[] decrypteddata = out.tobytearray();
out.close();
return decrypteddata;
}
/**
* <p>
* 公钥解密
* </p>
*
* @param encrypteddata
* 已加密数据
* @param publickey
* 公钥(base64编码)
* @return
* @throws exception
*/
public static byte[] decryptbypublickey(byte[] encrypteddata, string publickey) throws exception {
byte[] keybytes = base64utils.decode(publickey);
x509encodedkeyspec x509keyspec = new x509encodedkeyspec(keybytes);
keyfactory keyfactory = keyfactory.getinstance(key_algorithm);
key publick = keyfactory.generatepublic(x509keyspec);
cipher cipher = cipher.getinstance(keyfactory.getalgorithm());
cipher.init(cipher.decrypt_mode, publick);
int inputlen = encrypteddata.length;
bytearrayoutputstream out = new bytearrayoutputstream();
int offset = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputlen - offset > 0) {
if (inputlen - offset > max_decrypt_block) {
cache = cipher.dofinal(encrypteddata, offset, max_decrypt_block);
} else {
cache = cipher.dofinal(encrypteddata, offset, inputlen - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * max_decrypt_block;
}
byte[] decrypteddata = out.tobytearray();
out.close();
return decrypteddata;
}
/**
* <p>
* 公钥解密
* </p>
*
* @param encrypteddatastr
* 已加密数据
* @param publickey
* 公钥(base64编码)
* @return
* @throws exception
*/
public static string decryptbypublickey(string encrypteddatastr, string publickey) throws exception {
if(stringutils.isblank(encrypteddatastr)){
return new string("");
}
byte[] encrypteddata = base64utils.decode(encrypteddatastr);
byte[] decodeddata = decryptbypublickey(encrypteddata, publickey);
return new string(decodeddata, "utf-8");
}
/**
* <p>
* 公钥加密
* </p>
*
* @param source
* 源数据
* @param publickey
* 公钥(base64编码)
* @return 加密数据
* @throws exception
*/
public static string encryptbypublickey(string source, string publickey) throws exception {
byte[] data = source.getbytes("utf-8");
byte[] encryptdata = encryptbypublickey(data, publickey);
return base64utils.encode(encryptdata);
}
/**
* <p>
* 公钥加密
* </p>
*
* @param data
* 源数据
* @param publickey
* 公钥(base64编码)
* @return
* @throws exception
*/
public static byte[] encryptbypublickey(byte[] data, string publickey) throws exception {
byte[] keybytes = base64utils.decode(publickey);
x509encodedkeyspec x509keyspec = new x509encodedkeyspec(keybytes);
keyfactory keyfactory = keyfactory.getinstance(key_algorithm);
key publick = keyfactory.generatepublic(x509keyspec);
// 对数据加密
cipher cipher = cipher.getinstance(keyfactory.getalgorithm());
cipher.init(cipher.encrypt_mode, publick);
int inputlen = data.length;
bytearrayoutputstream out = new bytearrayoutputstream();
int offset = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputlen - offset > 0) {
if (inputlen - offset > max_encrypt_block) {
cache = cipher.dofinal(data, offset, max_encrypt_block);
} else {
cache = cipher.dofinal(data, offset, inputlen - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * max_encrypt_block;
}
byte[] encrypteddata = out.tobytearray();
out.close();
return encrypteddata;
}
/**
* <p>
* 私钥加密
* </p>
*
* @param data
* 源数据
* @param privatekey
* 私钥(base64编码)
* @return
* @throws exception
*/
public static byte[] encryptbyprivatekey(byte[] data, string privatekey) throws exception {
byte[] keybytes = base64utils.decode(privatekey);
pkcs8encodedkeyspec pkcs8keyspec = new pkcs8encodedkeyspec(keybytes);
keyfactory keyfactory = keyfactory.getinstance(key_algorithm);
key privatek = keyfactory.generateprivate(pkcs8keyspec);
cipher cipher = cipher.getinstance(keyfactory.getalgorithm());
cipher.init(cipher.encrypt_mode, privatek);
int inputlen = data.length;
bytearrayoutputstream out = new bytearrayoutputstream();
int offset = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputlen - offset > 0) {
if (inputlen - offset > max_encrypt_block) {
cache = cipher.dofinal(data, offset, max_encrypt_block);
} else {
cache = cipher.dofinal(data, offset, inputlen - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * max_encrypt_block;
}
byte[] encrypteddata = out.tobytearray();
out.close();
return encrypteddata;
}
/**
* <p>
* 私钥加密
* </p>
*
* @param source
* 源数据
* @param privatekey
* 私钥(base64编码)
* @return 加密数据
* @throws exception
*/
public static string encryptbyprivatekey(string source, string privatekey) throws exception {
byte[] data = source.getbytes("utf-8");
byte[] encryptdata = encryptbyprivatekey(data, privatekey);
return base64utils.encode(encryptdata);
}
/**
* <p>
* 获取私钥
* </p>
*
* @param keymap
* 密钥对
* @return
* @throws exception
*/
public static string getprivatekey(map<string, object> keymap) throws exception {
key key = (key) keymap.get(private_key);
return base64utils.encode(key.getencoded());
}
/**
* <p>
* 获取公钥
* </p>
*
* @param keymap
* 密钥对
* @return
* @throws exception
*/
public static string getpublickey(map<string, object> keymap) throws exception {
key key = (key) keymap.get(public_key);
return base64utils.encode(key.getencoded());
}
public static void main(string[] args) throws exception {
map<string, object> stringobjectmap = genkeypair();
// keymap.put(public_key, publickey);
// keymap.put(private_key, privatekey);
try {
//map<string, object> v = genkeypair();
string publickey = "migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqc1a31owvg2wnt53j3bcupbfq3s" +
"pp4dtwojazgyaanjdv/bikgdqjmttuqndntuifphqqhwxwp7bj6hlacb5tc2nhy5" +
"ii4u9tjp3o86mcrtndwqgzklhbtbirhoc5wc/ialkadoy1kgl5g9wfczq3tvjqso" +
"ugsvi83wclscbhkjgqidaqab";
string privatekey ="miicdwibadanbgkqhkig9w0baqefaascamewggjdageaaogbalvrfwha+dzae3nc" +
"ncek6lt+rdkmngo3cimbmbgaa0ko/9siqz1cmxo26qd01o6j8+gpafbfa/senoeu" +
"bwhm1zy2hlkgjht22m/ejzoxyu013cobmqudtnsisc4llyl8gaurp07luqavkb1z" +
"9znde1wnbi64ay+lzfakwwjugqmbagmbaaecgyeangmscdipssfo2z2qr45pq5vj" +
"32j9qborbm4k+9tw+a2szkx9bcdbiud1e/ekdjq6xxxzfanz9nie56r0/fct5rvm" +
"mfc9av9m6gmgnmgkcvg0usrlh8tv294jefhfwnwc1h+bsoblst1ybn+50fq6bmih" +
"wz2ran3qctv6z3emyrkcqqdyb2i6fzuryjxlljsz27so0pxltocrarjctzauvvm0" +
"a3/vw8nsuq3al2lxm73vqotvrhauf1noj7t9aupuedppakea1vzjfgrcl1fdrpvx" +
"4yor1mpdjfvcfj5q143wqlyjvp8meezfpk0iqq9brfk/+ehrrexvm3ehvomvqclo" +
"hrj7lwjbamkvtayxu6ol3jjrt2v+fkyq03duhkw3y/az1+3vi8/wmiov0b+o5mal" +
"mg1zxrb83+g1zlra/qwzodq1rp6m2amcqdyq5lz9k7qzvcko/g2vfybqgjoanwhj" +
"pdjslbz467idvcoqy6gpm2qz+jo/iqp8kkhkcp6m0vxwksbb26eu2pmcqck6lfnr" +
"xrr1qvnaas5mot202lpkogcewms3dtjeor8frm3n3xfwyasyvmvlo1nxua7yz6ui" +
"3jb38pdvwq5ncxa=";
system.out.println(publickey);
system.out.println(privatekey);
string s = rsautils.encryptbypublickey("{\"time\":,\"userid\":\"3a02ec335000433cadb216cb8f495b14\"}",publickey);
system.out.println(s);
string data=rsautils.decryptbyprivatekey(s, privatekey);
system.out.println(data);
} catch (exception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
}
上一篇: django之模型层
下一篇: 关羽放走了曹操,为何诸葛亮却没责怪他呢?