NET和Vue实现前后端RSA加密解密

前言

C#后端动态生成RSA公钥和私钥, Vue前端使用公钥对数据加密,后端使用私钥解密

vue前端

1.安装依赖

npm install jsencrypt --save

2.创建rsa.js文件 引用依赖

import { JSEncrypt } from 'jsencrypt'
 
//加密
//str 未加密字符串
export function setEncrypt(str){
  //实例化JSEncrypt
  let jse = new JSEncrypt();
  //加密公钥(由C#后端生成)
  let PUBLIC_KEY = `MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvnuBHhh9/Mwi4Z8Ea2IfVc7SJYyKkJT+4m4LBJbgxRVPa+ej1iAvJAJ++1CNfH6oVr6tw/wqEIZybTG7+iPm7SzfoW9eb/LYsLR43zLqriYWy7qAd7S/13zILiAGLUy/h9CDYwoXYaNXanVGe0iJb+NXmg7f4MAEo7rR15QHQ8zDtomPI/Fz9vz+o/xzHqsLVnxZIpn4dlCp+7QtzOePnvEda5xqWk4DNaVV2fr9gwfBFd8MyAP+CyBXLAWpmxinRU6knsLKAlqcbOLNjk2+aPNvH9EWHODKWBuMPpdDwQexD+V3/nOp8c07NzSfwXmlZuRKod9SqVY88Pg1r84WwQIDAQAB`

  jse.setPublicKey('-----BEGIN PUBLIC KEY-----' + PUBLIC_KEY + '-----END PUBLIC KEY-----');
  let  data = jse.encrypt(str.toString());  // 进行加密
  return data;
}

//解密
//params 待解密字符串
export function getDecrypt(params){
  //实例化JSEncrypt
  let jse = new JSEncrypt();
  //使用前端私钥解密(私钥由C#后端生成)
  let PRIVATE_KEY = `MIIEowIBAAKCAQEAvnuBHhh9/Mwi4Z8Ea2IfVc7SJYyKkJT+4m4LBJbgxRVPa+ej1iAvJAJ++1CNfH6oVr6tw/wqEIZybTG7+iPm7SzfoW9eb/LYsLR43zLqriYWy7qAd7S/13zILiAGLUy/h9CDYwoXYaNXanVGe0iJb+NXmg7f4MAEo7rR15QHQ8zDtomPI/Fz9vz+o/xzHqsLVnxZIpn4dlCp+7QtzOePnvEda5xqWk4DNaVV2f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7BOKqddE/Syh0dfK/FhKQ23bo0oUBH3tOipZvG/SVBdSzU5S6g+uRJf8xNOFw/c9JOnbQ6euUf2E5JYp7YN5nOuHMXVfzyF61zTjgnowKBgHqozPZH2yTU0bgQfZBsUBFB4vpUkfzB6o6qOOFQ4uiLqvW64LghE1yf7S5+XYz8ZXtIf7yb7sZcJE6XR9BD4gdYl/0KnWRL+oJQMUGDZDBzOcHiHQ8gdyACAC5hFexngJE0RNHtYcg2QjUNMfZMu/eUXJ1EjzisCT0xbwIXv0oZ`

  jse.setPrivateKey('-----BEGIN RSA PRIVATE KEY-----'+PRIVATE_KEY+'-----END RSA PRIVATE KEY-----');
  let data = jse.decrypt(params); //解密
  return data;
} 

3.创建test.vue文件使用加密和解密

<template>
    <div>
        <a-button type="primary"  @click="onTest">测试</a-button>
    </div>
</template>

<script>
    import {setEncrypt, getDecrypt} from '@/utils/rsa'
    export default {
        methods:{
            onTest() {
              let data = JSON.stringify({
                name: 'admin',
                passWord: '123456'
              })
              console.log('加密前', data)

              let encrypt = setEncrypt(data)
              console.log('加密后', encrypt)

              let decrypt = getDecrypt(encrypt)
              console.log('解密后', decrypt)
            }
        }
    }
</script>

<style lang="less" scoped>
</style>

NET后端

1.生成公钥和私钥

    class Program {
        
        static void Main(string[] args) {
            Console.WriteLine("---------------------------------------------------------");
            Console.WriteLine("◆◆◆◆◆◆◆◆◆◆◆◆ RSA测试 ◆◆◆◆◆◆◆◆◆◆◆◆");
            Console.WriteLine("---------------------------------------------------------");

            CreateRsa();

            Console.WriteLine("-------------------------------------------------------------");
            Console.WriteLine("◆◆◆◆◆◆◆◆◆◆◆◆ 回车退出... ◆◆◆◆◆◆◆◆◆◆◆◆");
            Console.WriteLine();
            Console.ReadLine();
        }
        static void CreateRsa()
        {
            //指定密钥大小创建一个新的RSA
            var rsa = new RSA(1024);
            Console.WriteLine("" + rsa.KeySize + "私钥(PKCS#1)】:");
            Console.WriteLine(rsa.ToPEM().ToPEM_PKCS1());
            Console.WriteLine();
            Console.WriteLine("" + rsa.KeySize + "公钥(PKCS#8)】:");
            Console.WriteLine(rsa.ToPEM().ToPEM_PKCS8(true));
            Console.WriteLine();

        }
    }

生成结果

 

 2.使用加密解密方法

 using (TextReader reader = new StringReader("-----BEGIN RSA PRIVATE KEY-----\r\nMIICWwIBAAKBgQCRmUrzhS7G0GQ5xXJzL59G+yNcsyGD/W66P2ufq7ZjIvAFPxLj\r\nnhEpWlV1Wl6ksfB7YkTE3FmV1hh2Acj7f4NXtxkep4iPQMxda3covTrNkZLNPhPr\r\nBVRscYE41/ofdo4bTADJkjnKNCGEQWl6wPTZCJVUWnOc0UCnz/oi9EuvuwIDAQAB\r\nAoGAECMEvxOqOQe8q/h5tFF5XjUUWMBTvRy4CnVf+LzfxIIJRxOUBN0uer5TzWNc\r\nLPW5uPsNsyHW3ffyExYkj9c0l7fHBoSO6WI6VvJc3/GK3FanB7h+Du/mJveG5ZDg\r\nnk1Igl2r8fu2Y9h1gox2uVK2zCHqCkzynisZC059K07lyEUCQQDNdyWu0PxiF3cI\r\ndngKif2++du8leMRgnjN/PIt4QgE50/x+zyYKxblLa5K1sqw7LEzyAqyqahb1jqx\r\n8vbPFS1FAkEAtWi5hzJDOsaNKFganH5PcXw5MVqGRV+NVap6YFwM2zvWyD0Swpq1\r\nQI9jWSkVn1mqFpkDIZRzCE7nSryekKK4/wJAaq5ulnJUWOouF+rLMU2svrgk66o3\r\nmCPSbcHkTQYGj+U6kT4NnETjQmORl7Im0+5Ro70+ML3+eJCnMTYiCCvKsQJAIMBf\r\nfoEckif2pCoD4+0J+rsquDZXt36gza6RmYQE7i/Hfy9Hi8rSnm1EynwYY0SU6K+H\r\nWTCr8/wK1ftnxUUbkQJAUxFvcWTB/eJtA5h5vUf8J+BFatQkAKeGYJSeKcZfamaO\r\n9JKpp+hZwV5qqbQxsZ1PgWO4D1nosK6vmsCAvkl/yA==\r\n-----END RSA PRIVATE KEY-----\r\n"))
            {
                dynamic key = new PemReader(reader).ReadObject();
                var rsaDecrypt = new Pkcs1Encoding(new RsaEngine());
                if (key is AsymmetricKeyParameter)
                {
                    key = (AsymmetricKeyParameter)key;
                }
                else if (key is AsymmetricCipherKeyPair)
                {
                    key = ((AsymmetricCipherKeyPair)key).Private;
                }
                rsaDecrypt.Init(false, key);  //这里加密是true;解密是false  

                byte[] entData = Convert.FromBase64String(sadada);
                entData = rsaDecrypt.ProcessBlock(entData, 0, entData.Length);
                address = Encoding.UTF8.GetString(entData);
            }

 

posted @ 2021-10-20 14:52  netlock  阅读(1977)  评论(0编辑  收藏  举报