首页 > 代码库 > C#中RSA的简单使用
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 =http://www.mamicode.com/ 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的简单使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。