Using the asymmetric algorithm Private and public key with RSA C #

I have two AsymmetricAlgorithm objects that contain the RSA Private and RSA public key. The private key was extracted from the Windows-MY keystore and public key from the user certificate. How can I use these keys with RSACryptoServiceProvider to encrypt data using the RSA algorithm in C #? In other words, how can I indicate that I want to use the keys that I already have?

+4
source share
1 answer
#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 

The public key (arg) should look like this: <RSAKeyValue> <& gt module; yNi8BvATA77f + / 6cU6z [...] 9VULgU = </ & gt module; <& exponent GT; AQAB </ & exponent GT; </RSAKeyValue>

The private key (arg) should look like this: <RSAKeyValue> <& gt module; yNi8BvATA77f + / 6cU6z [...] 9VULgU = </ & gt module; <& exponent GT; AQAB </ & exponent GT; <P> 8ZlZPmko3sam9pvD / l [...] ba0MWLjj9dyUMvmTQ6L8m9IQ == </P> & L, Q> 1NGHjXyEa9SjUwY [...] V + op2YyyglMeK / Gt5SL0v6xqQQ = & =) LpjE / aSKnWzzBt1E [...] i5f63Ak9wVG3ZPnwVDwefNkMAQ == </DP> <& DQ GT; qAgb8AGNiJom [...] 8x3qaD3wx + UbnM5v3aE5Q == </DQ> <InverseQ> fQ4 + 7r3Nmgvz113L [...] uJqEgCNzw == </InverseQ> <D> B4n7JNeGHzHe / nqEK = ... </RSAKeyValue>

+2
source

Source: https://habr.com/ru/post/1315114/


All Articles