MyRapid MyRapidMyRapid

加密函数之RSA

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace NBest.Code
{
    //RSA公开密钥密码体制是一种使用不同的加密密钥与解密密钥,“由已知加密密钥推导出解密密钥在计算上是不可行的”密码体制
    public static class RSA
    {
        private static System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        //RSA的加密函数   
        public static  string Encrypt(string xmlPublicKey, string EncryptString)
        {
            byte[] PlainTextBArray;
            byte[] CypherTextBArray;
            string Result;
            
            rsa.FromXmlString(xmlPublicKey);
            PlainTextBArray = (new UnicodeEncoding()).GetBytes(EncryptString);
            CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
            Result = Convert.ToBase64String(CypherTextBArray);
            return Result;
        }
        //RSA的解密函数   
        public static string Decrypt(string xmlPrivateKey, string DecryptString)
        {
            byte[] PlainTextBArray;
            byte[] DypherTextBArray;
            string Result;
            //System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(xmlPrivateKey);
            PlainTextBArray = Convert.FromBase64String(DecryptString);
            DypherTextBArray = rsa.Decrypt(PlainTextBArray, false);
            Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
            return Result;
        }
        //RSA   的密钥产生   
        //产生私钥   和公钥
        public static void GetKey(out string xmlKeys, out string xmlPublicKey)
        {
            //System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            xmlKeys = rsa.ToXmlString(true);
            xmlPublicKey = rsa.ToXmlString(false);
        }
    }
}


创作不易,转载请保留原文连接:加密函数之RSA

点赞(118) 打赏

发表评论

热门评论

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏