1. 程式人生 > >C#中RSA的簡單使用

C#中RSA的簡單使用

[] 實例 enc add eat creat sta int padding

        static void Main(string[] args)
        {
            try
            {
                //創建一個編碼實例用來將字符串轉換成byte數組
                UnicodeEncoding ByteConverter = new UnicodeEncoding();

                //Create byte arrays to hold original, encrypted, and decrypted data.
                byte[] dataToEncrypt = ByteConverter.GetBytes("
Data to Encrypt"); byte[] encryptedData; byte[] decryptedData; using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { encryptedData = RSAEncrypt(dataToEncrypt, RSA.ExportParameters(false), false); decryptedData
= RSADecrypt(encryptedData, RSA.ExportParameters(true), false); Console.WriteLine("Decrypted plaintext: {0}", ByteConverter.GetString(decryptedData)); } } catch (ArgumentNullException) { Console.WriteLine("Encryption failed.
"); } Console.Read(); } static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding) { try { byte[] encryptedData; //創建一個RSACryptoServiceProvider實例. using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { //指定共有鑰匙 RSA.ImportParameters(RSAKeyInfo); //加密,並且指定是否運行在XP更高的版本中 encryptedData = RSA.Encrypt(DataToEncrypt, DoOAEPPadding); } return encryptedData; } catch (CryptographicException e) { Console.WriteLine(e.Message); return null; } } static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding) { try { byte[] decryptedData; using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSA.ImportParameters(RSAKeyInfo); decryptedData = RSA.Decrypt(DataToDecrypt, DoOAEPPadding); } return decryptedData; } //Catch and display a CryptographicException //to the console. catch (CryptographicException e) { Console.WriteLine(e.ToString()); return null; } }

技術分享

C#中RSA的簡單使用