使用带有RSA C#的非对称算法私钥和公钥
我有两个包含RSA Private和RSA公钥的AsymmetricAlgorithm对象。 从Windows-MY密钥库中检索私钥,从用户证书中检索公钥。 如何使用这些密钥和RSACryptoServiceProvider在C#中使用RSA算法加密数据? 换句话说,我如何指定我想使用已有的密钥?
#region "RSA Encrypt/Decrypt" public string RSAEncrypt(string str, string publicKey) { //---Creates a new instance of RSACryptoServiceProvider--- try { RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); //---Loads the public key--- RSA.FromXmlString(publicKey); byte[] EncryptedStr = null; //---Encrypts the string--- EncryptedStr = RSA.Encrypt(ASCII.GetBytes(str), false); //---Converts the encrypted byte array to string--- int i = 0; System.Text.StringBuilder s = new System.Text.StringBuilder(); for (i = 0; i <= EncryptedStr.Length - 1; i++) { //Console.WriteLine(EncryptedStr(i)) if (i != EncryptedStr.Length - 1) { s.Append(EncryptedStr[i] + " "); } else { s.Append(EncryptedStr[i]); } } return s.ToString(); } catch (Exception err) { Interaction.MsgBox(err.ToString()); } } public string RSADecrypt(string str, string privateKey) { try { //---Creates a new instance of RSACryptoServiceProvider--- RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); //---Loads the private key--- RSA.FromXmlString(privateKey); //---Decrypts the string--- byte[] DecryptedStr = RSA.Decrypt(HexToByteArr(str), false); //---Converts the decrypted byte array to string--- System.Text.StringBuilder s = new System.Text.StringBuilder(); int i = 0; for (i = 0; i <= DecryptedStr.Length - 1; i++) { //Console.WriteLine(DecryptedStr(i)) s.Append(System.Convert.ToChar(DecryptedStr[i])); } //Console.WriteLine(s) return s.ToString(); } catch (Exception err) { Interaction.MsgBox(err.ToString()); } } #endregion
公钥(arg)应如下所示:
私钥(arg)应如下所示:
8ZlZPmko3sam9pvD / l [...] ba0MWLjj9dyUMvmTQ6L8m9IQ ==
1NGHjXyEa9SjUwY [...] v + op2YyyglMeK / Gt5SL0v6xqQZQ ==
上述就是C#学习教程:使用带有RSA C#的非对称算法私钥和公钥分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1025369.html