网页登录时用RSA对用户名和密码进行加解密

为什么80%的码农都做不了架构师?>>>   hot3.png

什么是RSA这里就不多说了,度娘上说的很详细,至于生成公钥私钥,建议使用linux来生成,前台使用公钥加密,后台使用私钥解密,这样只要私钥不泄露,黑客破解你的密码就只剩下理论上的可能;

一、首先前台

1、在你的登录页面引入一个js文件:jsencrypt.js,这个文件是用来在前台对用户名和密码进行RSA加密的

登陆页面代码如下:(自己测试用的页面,很low比,将就着看)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>




登录页面

用户名:
密码:

二、在后台对接收的用户名和密码进行解密

package you.you.an.controller;


import com.jfinal.core.Controller;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.pkcs.RSAPrivateKeyStructure;
import org.bouncycastle.util.encoders.Base64;
import you.you.an.util.ConfigFileUtil;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.RSAPrivateKeySpec;


/**
 *
 */

public class SessionController extends Controller{

//    private static final Logger logger = Logger.getLogger(SessionController.class);
    private static final String privateStr = ConfigFileUtil.getPrivateKey();
    private static KeyFactory kf = null;
    private static RSAPrivateKeyStructure asn1PrivKey = null;
    private static RSAPrivateKeySpec rsaPrivKeySpec = null;
    private static PrivateKey rsaPriKey = null;
    private static Cipher cipher = null;
    static {
        try {
            if (asn1PrivKey == null){
                asn1PrivKey = new RSAPrivateKeyStructure((ASN1Sequence) ASN1Sequence.fromByteArray(Base64.decode(privateStr)));
                if (rsaPrivKeySpec == null){
                    rsaPrivKeySpec = new RSAPrivateKeySpec(asn1PrivKey.getModulus(), asn1PrivKey.getPrivateExponent());
                    if (kf == null){
                        kf = KeyFactory.getInstance("RSA");
                        if (rsaPriKey == null){
                            rsaPriKey = kf.generatePrivate(rsaPrivKeySpec);
                            if (cipher == null){
                                cipher = Cipher.getInstance("RSA");
                                cipher.init(Cipher.DECRYPT_MODE, rsaPriKey);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void login() {
        String username = getPara("username");
        String password = getPara("password");
        System.out.println(username);
        System.out.println(password);
        try {
            byte[] passwordByte = cipher.doFinal(Base64.decode(password));
            byte[] usernameByte = cipher.doFinal(Base64.decode(username));
            System.out.println("解密后密码为:"+new String(passwordByte));
            System.out.println("解密后用户名为:"+new String(usernameByte));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

这里解释一下为什么要使用静态代码块来初始化Cipher对象,因为这个对象的初始化是非常慢的,即便是采用了静态,还是怕影响效率,最终采用了MD5来加密,上述方法是个好方法,但前提是得解决java环境下RSA的运行效率问题!

转载于:https://my.oschina.net/ayo123/blog/1543850

你可能感兴趣的:(网页登录时用RSA对用户名和密码进行加解密)