rsa+aes非对称加密实例(两对公私钥)




html



    
    测试页
    
    
    
   
    



   
   
   


js
/**
 * Created by Administrator on 2017/5/1.
 */
/**
 * Created by Administrator on 2017/5/1.
 */
requirejs.config({
    baseUrl: 'js/lib',       //相对路径,指定模块的基准路径,相对于加载此
    //data-main文件的html文件
    shim: {
        'bootstrap': {
            deps: ['jquery']
        },
        'datatables': {
            deps: ['jquery']
        },
        /* 'jqueryform': {
         deps: ['jquery']
         },*/
        'gVerify': {
            deps: ['jquery']
        },
    },
    paths: {
        jquery: 'jquery',
        datatables: 'datatables',
        gVerify: 'gVerify',
        //jqueryform:'jquery-form',
        mod: '../module',        //相对路径,相对于baseUrl,注意下方的使用别名
        bootstrap: 'bootstrap-3.3.7-dist/js/bootstrap',
        aes: 'aes',
        jsencrypt: 'jsencrypt',
    }
});

require(['jquery', 'datatables', /*'jqueryform',*/ 'mod/test', 'bootstrap', 'gVerify', 'mod/util', 'jsencrypt', 'aes'],
    function ($, datatables, test, bootstrap, gVerify, util, jsencrypt, aes) {// 这里的参数,和前边的模块是按
        $(function () {


            console.log(jsencrypt);
            console.log(CryptoJS)


            document.addEventListener('click', function (event) {
                if (event.target.id == 'btn_test') {

                    var request = {};
                    var data = $('#data').val();

                    if (data != "") {
                        var password = getAesKey16();

                        var pubkey = $('#ServerPubkey')[0].innerHTML;
                        var prikey = $('#ClientPrikey')[0].innerHTML;
                        var encryptor = new jsencrypt.JSEncrypt();
                        encryptor.setPublicKey(pubkey);
                        var decryptor = new jsencrypt.JSEncrypt();
                        decryptor.setPublicKey(prikey);

                        request["code"] = encryptor.encrypt(password);

                        var aeskey = CryptoJS.enc.Latin1.parse(password);

                        request["object"] = CryptoJS.AES.encrypt(data, aeskey, {
                            iv: aeskey,
                            mode: CryptoJS.mode.CBC,
                            padding: CryptoJS.pad.ZeroPadding
                        }).toString();

                        $.ajax({
                            type: 'POST',
                            url: "/ldps/test/test",
                            contentType: "application/json; charset=utf-8", //注意这个写法.
                            dataType: "json",
                            data: JSON.stringify(request),
                            beforeSend: function () {
                            },
                            success: function (response) {
                                console.log(response);
                                console.log(decryptor.decrypt(response.code));
                                aeskey = CryptoJS.enc.Latin1.parse(decryptor.decrypt(response.code).trim());
                                var result = CryptoJS.AES.decrypt(response['object'], aeskey, {
                                    iv: aeskey,
                                    mode: CryptoJS.mode.CBC,
                                    padding: CryptoJS.pad.ZeroPadding
                                }).toString(CryptoJS.enc.Utf8);

                                console.log(result);

                            },
                            error: function (event) {
                            },
                        });


                    }
                }
            }, null);


        });

        function getAesKey16() {
            var oKey = Math.round(Math.random() * 1E16) + "";
            if (oKey.length < 16) {
                for (var n = 0; n < 16 - oKey.length; n++) {
                    oKey += '0';
                }
            }
            return oKey;
        }


    });


java


@Controller
@RequestMapping(value="/test")
public class TestController {
    
    @RequestMapping(value="/test")
    public @ResponseBody Message test(@RequestBody Message request,HttpSession session) throws Exception {
        
        String priString = IOUtils.toString(Thread.currentThread().getContextClassLoader().getResourceAsStream("server_pkcs8_rsa_priv.pem"));
        String pubString = IOUtils.toString(Thread.currentThread().getContextClassLoader().getResourceAsStream("client_pub.pem"));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(priString));
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(pubString));
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyFactory.generatePublic(x509EncodedKeySpec);
        
        //解密器
        Cipher decryptor = Cipher.getInstance("RSA");
        decryptor.init(Cipher.DECRYPT_MODE, rsaPrivateKey);
        //加密器
        Cipher encryptor = Cipher.getInstance("RSA");
        encryptor.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
    
        //开始解密
        String aesPassword = new String(decryptor.doFinal(Base64.decodeBase64(request.getCode())));
        
        SecretKeySpec skeySpec = new SecretKeySpec(aesPassword.getBytes(), "AES");
        IvParameterSpec ivps = new IvParameterSpec(aesPassword.getBytes());
        Cipher aesCipher = Cipher.getInstance("AES/CBC/NoPadding"); //"算法/模式/补码方式";
        aesCipher.init(Cipher.DECRYPT_MODE, skeySpec, ivps); 

        System.out.println("前台发送的随机数:"+aesPassword);
        System.out.println("前台发送的数据:"+(new String(aesCipher.doFinal(Base64.decodeBase64((String)request.getObject())))).trim());
        
        
        //开始加密
        
        Message response = new Message();
        aesPassword = LdpsUtil.getAesKey16();

        skeySpec = new SecretKeySpec(aesPassword.getBytes(), "AES");
        ivps = new IvParameterSpec(aesPassword.getBytes());
        aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivps); 
        
        response.setCode(Base64.encodeBase64String(encryptor.doFinal(aesPassword.getBytes())));
        response.setObject(Base64.encodeBase64String(aesCipher.doFinal(LdpsUtil.padByteArrayTo16s("返回数据测试".getBytes("UTF-8")))));
        
        return response;
    }
    
    
}



你可能感兴趣的:(JAVA,安全加密)