C#中RSA的简单使用
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; } }
Hold on, everything is possible.
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步