.net中RSA的加密与解密

        #region
        /// 
        /// RSA获取公钥私钥
        /// 
        /// 
        /// 
        public  void RSACreateKey(ref string str_PublicKey, ref string str_PrivateKey)
        {
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(512);
            //str_PublicKey = Convert.ToBase64String(RSA.ExportCspBlob(false));
            //str_PrivateKey = Convert.ToBase64String(RSA.ExportCspBlob(true));

            str_PublicKey = RSA.ToXmlString(false);
            str_PrivateKey = RSA.ToXmlString(true);
        }

        /// 
        /// RSA加密
        /// 
        /// 
        /// 
        /// 
        /// 
        public  string RSAEncrypt(string source, string str_PublicKey)
        {
            try
            {
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

                RSA.FromXmlString(str_PublicKey);

                //str_PublicKey = Convert.ToBase64String(RSA.ExportCspBlob(false));
                //str_PrivateKey = Convert.ToBase64String(RSA.ExportCspBlob(true));
                byte[] DataToEncrypt = Encoding.UTF8.GetBytes(source);

                byte[] bs = RSA.Encrypt(DataToEncrypt, false);
                //str_PublicKey = Convert.ToBase64String(RSA.ExportCspBlob(false));
                //str_PrivateKey = Convert.ToBase64String(RSA.ExportCspBlob(true));
                string encrypttxt = Convert.ToBase64String(bs);

                return encrypttxt;
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }

        /// 
        /// RSA解密
        /// 
        /// 
        /// 
        /// 
        public  string RSADecrypt(string strRSA, string str_PrivateKey)
        {
            try
            {
                byte[] DataToDecrypt = Convert.FromBase64String(strRSA);
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

                RSA.FromXmlString(str_PrivateKey);
                //byte[] bsPrivatekey = Convert.FromBase64String(str_PrivateKey);
                //RSA.ImportCspBlob(bsPrivatekey);

                byte[] bsdecrypt = RSA.Decrypt(DataToDecrypt, false);

                string strRE = Encoding.UTF8.GetString(bsdecrypt);
                return strRE;
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.ToString());
                return null;
            }
        }
        #endregion


你可能感兴趣的:(Asp.net,加密,.net,string,byte,解密,null)