1. 程式人生 > >C# RSA加密解密

C# RSA加密解密

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

namespace ConsoleApplication2
{
    class RSACryption
    {
        static void Main(string[] args)
        {
            //產生一對公鑰,私鑰
            RSACryptoServiceProvider rsa = new
RSACryptoServiceProvider(); string xmlKeys = rsa.ToXmlString(true); //私鑰 string xmlPublicKey = rsa.ToXmlString(false); //公鑰 string EncryptString = RSAEncrypt(xmlPublicKey, "1223345611"); Console.WriteLine(EncryptString); Console.WriteLine("------------------------------------"
); string DecryptString = RSADecrypt(xmlKeys, EncryptString); Console.WriteLine(DecryptString); Console.ReadKey(); } /// <summary> /// RSA的加密函式 /// </summary> /// <param name="xmlPublicKey">公鑰</param> /// <param name="encryptString">
待加密的字串</param>
/// <returns></returns> public static string RSAEncrypt(string xmlPublicKey, string encryptString) { try { byte[] PlainTextBArray; byte[] CypherTextBArray; string Result; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(xmlPublicKey); PlainTextBArray = (new UnicodeEncoding()).GetBytes(encryptString); CypherTextBArray = rsa.Encrypt(PlainTextBArray, false); Result = Convert.ToBase64String(CypherTextBArray); return Result; } catch (Exception ex) { throw ex; } } /// <summary> /// RSA的解密函式 /// </summary> /// <param name="xmlPrivateKey">私鑰</param> /// <param name="decryptString">待解密的字串</param> /// <returns></returns> public static string RSADecrypt(string xmlPrivateKey, string decryptString) { try { 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; } catch (Exception ex) { throw ex; } } } }