i am trying to get session from my Chrome browser. i can see 2 cookie files in Developer Tools. but this is inconvenient for the user to get cookie values from browser, i would like to do it in code. so i use this code to get Chrome default profile cookie sqlite DB:
string local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string path = #"Google\Chrome\User Data\Default\Cookies";
path = Path.Combine(local, path);
next i create SQLite connection and request
var cmd = new SQLiteCommand("SELECT encrypted_value, name FROM cookies WHERE host_key = 'my_host_ip'", con);
then i read the results
byte[] encryptedCookie = (byte[])r.GetValue(r.GetOrdinal("encrypted_value"));
and try to decrypt it:
var decodedData = ProtectedData.Unprotect(encryptedCookie, null, DataProtectionScope.CurrentUser);
var plainText = Encoding.ASCII.GetString(decodedData);
and here i got exception
System.Security.Cryptography.CryptographicException
i know that i MUST decrypt cookie contents under the same user account under which the browser was launched (on the same machine), and parameter DataProtectionScope.CurrentUser is used for that
i see 63 bytes in debugger (in encryptedCookie array), i also see this bytes in SQLite DB BLOB field.
but Unprotect method throws System.Security.Cryptography.CryptographicException: Invalid data error.
my code works fine at 5 different PC's in my office (win10, win7), but didnt work on my developer PC (win10, vs2019).
i think that the problem is in my Windows Settings or somewhere else, not in my code. so what i am doing wrong?
interesting note - i found PowerShell script that does the same thing (through Add-Type -AssemblyName System.Security) - get cookie and decrypt it. this script also works fine at 5 office PC's, but didnt work at my PC.
my Windows installation is new, i have no AV software. we connected to the same Corporate domain and we have the same security settings.
UPD 1
a little expreriment:
get cookie value from Chrome browser (32 chars, JSESSIONID)
create a simple app that protects this value with CurrentUser protection scope. now i have an array of 178 bytes (result #1)
view Chrome's cookies database with a) https://sqliteonline.com/ and b) DataBase.Net desktop app. this two methods give me the same result: only 63 bytes of encrypted cookie data (result #2). i can also get the same result with my c# application using System.Data.SQLite
so, the results are not equal in length or content
result #1 != result #2
looks like Chrome's cookie value protected by different scope (maybe admin account?), but i see my user account name in Task Manager in Chrome's process
P.S. i use .net 4.7.2
UPD 2
i found this method in Chromium sources
bool OSCrypt::DecryptString(const std::string& ciphertext,
std::string* plaintext) {
if (!base::StartsWith(ciphertext, kEncryptionVersionPrefix,
base::CompareCase::SENSITIVE))
return DecryptStringWithDPAPI(ciphertext, plaintext);
crypto::Aead aead(crypto::Aead::AES_256_GCM);
auto key = GetEncryptionKeyInternal();
aead.Init(&key);
// Obtain the nonce.
std::string nonce =
ciphertext.substr(sizeof(kEncryptionVersionPrefix) - 1, kNonceLength);
// Strip off the versioning prefix before decrypting.
std::string raw_ciphertext =
ciphertext.substr(kNonceLength + (sizeof(kEncryptionVersionPrefix) - 1));
return aead.Open(raw_ciphertext, nonce, std::string(), plaintext);
}
so DPAPI is only used when BLOB NOT starts with v10 chars. but my cookie BLOBs starts with v10 chars, and, according to the code, another crypto-algorithm is used, but i dont understand WHY.
I finally figured it out. according to Chromium sources, two methods are used to decrypt the cookie value.
if the cookie value starts with v10 chars, we use AES_256_GCM
otherwise, DPAPI is used
for the first method we need key and nonce. key is located in Google Chrome files and nonce is located in encrypted cookie value.
it remains unclear for me - what determines which method is used
For people who are looking for the code, I'm expanding on Cerberus answer. Starting Chrome 80 version, cookies are encrypted using the AES256-GCM algorithm, and the AES encryption key is encrypted with the DPAPI encryption system, and the encrypted key is stored inside the ‘Local State’ file.
byte[] encryptedData=<data stored in cookie file>
string encKey = File.ReadAllText(localAppDataPath + #"\Google\Chrome\User Data\Local State");
encKey = JObject.Parse(encKey)["os_crypt"]["encrypted_key"].ToString();
var decodedKey = System.Security.Cryptography.ProtectedData.Unprotect(Convert.FromBase64String(encKey).Skip(5).ToArray(), null, System.Security.Cryptography.DataProtectionScope.LocalMachine);
_cookie = _decryptWithKey(encryptedData, decodedKey, 3);
Key size is 256 bits. Encypted message format is, pay load('v12')+nonce (12 bytes)+cipherText
private string _decryptWithKey(byte[] message, byte[] key, int nonSecretPayloadLength)
{
const int KEY_BIT_SIZE = 256;
const int MAC_BIT_SIZE = 128;
const int NONCE_BIT_SIZE = 96;
if (key == null || key.Length != KEY_BIT_SIZE / 8)
throw new ArgumentException(String.Format("Key needs to be {0} bit!", KEY_BIT_SIZE), "key");
if (message == null || message.Length == 0)
throw new ArgumentException("Message required!", "message");
using (var cipherStream = new MemoryStream(message))
using (var cipherReader = new BinaryReader(cipherStream))
{
var nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength);
var nonce = cipherReader.ReadBytes(NONCE_BIT_SIZE / 8);
var cipher = new GcmBlockCipher(new AesEngine());
var parameters = new AeadParameters(new KeyParameter(key), MAC_BIT_SIZE, nonce);
cipher.Init(false, parameters);
var cipherText = cipherReader.ReadBytes(message.Length);
var plainText = new byte[cipher.GetOutputSize(cipherText.Length)];
try
{
var len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0);
cipher.DoFinal(plainText, len);
}
catch (InvalidCipherTextException)
{
return null;
}
return Encoding.Default.GetString(plainText);
}
}
Needed packages
1) Newtonsoft JSON .net
2) Bouncy Castle Crypto package
Related
I've written a C# piece that encrypts/decrypts a string using RtlEncryptMemory/RtlDecryptMemory. This string is then saved in a config file, it all works well but the problem is that once I logoff/logon, I can no longer decrypt the string. I am using the RTL_ENCRYPT_OPTION_SAME_LOGON option which means the internal mechanism uses something from the Windows session in order to perform the decryption. I am looking for a solution that works in the same manner but is tied to the network user (or token, etc...). Is Windows providing something already?
My goal is to be able to decrypt the string from anywhere as long as the process is running under the same user (network credentials). I also do not want to have the user type in a password or use an internal value as that could be compromised. Ideally it would be just like the RTL functions but provide an RTL_ENCRYPT_OPTION_SAME_USER option.
You want to use the DataProtection API
Here is a simple implementation that adds Encrypt and Decrypt string extensions...
public static class StringExtensions
{
public static string Encrypt(this string s)
{
if (String.IsNullOrEmpty(s))
{
return s;
}
else
{
var encoding = new UTF8Encoding();
byte[] plain = encoding.GetBytes(s);
byte[] secret = ProtectedData.Protect(plain, null, DataProtectionScope.CurrentUser);
return Convert.ToBase64String(secret);
}
}
public static string Decrypt(this string s)
{
if (String.IsNullOrEmpty(s))
{
return s;
}
else
{
byte[] secret = Convert.FromBase64String(s);
byte[] plain = ProtectedData.Unprotect(secret, null, DataProtectionScope.CurrentUser);
var encoding = new UTF8Encoding();
return encoding.GetString(plain);
}
}
}
Here is an example...
class Program
{
static void Main(string[] args)
{
string password = "Monkey123";
string encrypted = password.Encrypt();
Console.WriteLine($"Encrypted password = '{encrypted}'");
string decrypted = encrypted.Decrypt();
Console.WriteLine($"Decrypted password = '{decrypted}'");
}
}
Which produces this output...
Encrypted password = 'AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAA/6wDgM21DkStrNJQ35QDiwAAAAACAAAAAAAQZgAAAAEAACAAAAAPr3/aqafbt/RRoPVe75b+PFBhE6h9MLcQ2Ivsd3adOwAAAAAOgAAAAAIAACAAAABYxqEdzotL+7qXpWnbbpPRkfWZF6oh/meFsXzFtLPnrBAAAAB59VGbboP4Tye1N3dB7E3jQAAAAMQn8cAlnTDe1mwDEJriADizdT2Qr0DtPgpMje+rbjdkVpL+cKiEQs4om4i1hlLPgPn5MG5oVWFFnxU0d4c9TFg='
Decrypted password = 'Monkey123'
Notes:
Only the currently logged in user can decrypt the data encrypted with this code. This works across the network as long as the current user has a roaming profile.
Alternatively the scope can be local machine in which case only users logged in to the same machine can decrypt the data.
This is .NET Core 3.1 code and works only on Windows machines
Using statements...
using System;
using System.Security.Cryptography;
using System.Text;
You should not be using RtlEncryptMemory if you want to store the string, it is meant to only keep strings secure inside the running applications memory, it therefore can be stored/serialized and decrypted.
Have a look at DPAPI password encryption I think it should meet your needs.
I have a Nuget package you might like:
DataJuggler.Net.Cryptography .Net Framework
DataJuggler.Core.Cryptography Dot Net Core
Pretty simple to work with, here is a live demo:
https://blazorcrypto.datajuggler.com/
Source code and video link is available above also.
Usage:
Encryption:
// get the encryptedText
encryptedResult = CryptographyHelper.EncryptString(textToEncrypt, keyCode);
Decryption:
// get thedecryptedText
decryptedResult = CryptographyHelper.DecryptString(textToDecrypt, keyCode);
It also includes password hashing.
Let me know if you think it is worth the price of free.
I am in need of assistance with signing a string in PHP. We are building a web application which is able to alter profile data on an external website. We want to achieve this without requiring end users to enter our password on our site. The external website therefore created an API which allows us to edit the profile as long we send them email address of the profile signed by a certificate. This allows them to check whether the request came from a trusted source (us).
We tried both native PHP functions and PHPSeclib to sign an email address using a certificate:
$rsa = new RSA();
$rsa->setHash("sha1");
$rsa->setSignatureMode(RSA::SIGNATURE_PKCS1);
$originalkey = file_get_contents('key.ppk');
$rsa->loadKey($originalkey);
echo bin2hex($rsa->sign("test#email.nl"));
// Using native PHP methods
$email = 'test#email.nl';
$signature = '';
$private_key = openssl_pkey_get_private(file_get_contents("key.ppk"));
var_dump(openssl_sign($email, $signature, $private_key, "sha1"));
echo bin2hex($signature);
The signatures are fine because PHP is able to verify the posted signatures. The webservice of the external website does not accept our signatures however. They only allow a signature length of 40 characters whilst a hexidecimal dump of our signature exceeds 1000 characters.
They sent us this C# example to sign a string but we do not have enough C# knowledge to see why the output differs.
string Sign(string username, string thumbprint, string hasher = "SHA1")
{
var store = new
System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine);
store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.OpenExistingOnly |
System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
try
{
foreach (System.Security.Cryptography.X509Certificates.X509Certificate2 certificate in store.Certificates.Find(System.Security.Cryptography.X509Certificates.X509FindType.FindByThumbprint, thumbprint, false))
{
var privateKey = certificate.PrivateKey as System.Security.Cryptography.RSACryptoServiceProvider;
if (privateKey != null)
{
var bytes = privateKey.SignData(Encoding.UTF8.GetBytes(username),
System.Security.Cryptography.HashAlgorithm.Create(hasher));
return string.Join("", bytes.Select(b => b.ToString("x2")));
} else throw new ArgumentException("no private key");
}
}
finally
{
store.Close();
}
return null;
}
Is there anyone who can point us to the right direction?
Thanks in advance!
I've written an ASP.NET Core 2.0 website in C# and have Facebook authentication enabled, so it requires HTTPS. I'm using the native Kestrel web server to host the site and have a listener set to take the PFX certificate per MS' documentation. I can't seem to find a way for Kestrel to recognize the private key after recall from Key Vault. I know it's present, as I wrote two debug statements that indicate it is, in fact present.
This is the function that I'm using to retrieve the secret, which is working.
public static async Task<X509Certificate2> GetKeyVaultCert()
{
X509Certificate2 pfx;
try
{
var kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));
var secret = await kvClient
.GetSecretAsync("https://macscampvault.vault.azure.net/secrets/letsencrypt").ConfigureAwait(false);
byte[] bytes;
if(secret.ContentType == "application/x-pkcs12")
bytes = Convert.FromBase64String(secret.Value);
else
{
bytes = new byte[0];
Console.WriteLine("secret is not PFX!!");
throw new ArgumentException("This is not a PFX string!!");
}
var password = new SecureString();
var coll = new X509Certificate2Collection();
coll.Import(bytes, null, X509KeyStorageFlags.Exportable);
pfx = coll[0];
// File output added in case I end up needing to write cert to container
// File.WriteAllBytes(Directory.GetCurrentDirectory().ToString() + "/Macs.pfx", bytes);
Console.WriteLine(pfx.HasPrivateKey);
Console.WriteLine(pfx.GetRSAPrivateKey());
}
catch (Exception ex)
{
Console.WriteLine($"There was a problem during the key vault operation\n{ex.Message}");
throw;
}
return pfx;
}
The debug statements after the assignment call pfx = coll[0]; tell me that this private key exists, but when I try to connect to the website using lynx https://localhost I receive the following exception:
System.NotSupportedException: The server mode SSL must use a certificate with the associated private key.
So, how do I use the private key? Here's a gist to the file in question.
I already was helped by How to serialize and deserialize a PFX certificate in Azure Key Vault? but after following it, I got to this state.
In your gist you have the following code:
var keyVaultCert = GetKeyVaultCert().Result ??
throw new ArgumentNullException("GetKeyVaultCert().Result");
pfx = new X509Certificate2(keyVaultCert.RawData);
The second line there removes the private key, because the RawData property just returns the DER encoded X.509 object.
keyVaultCert is already an X509Certificate2 with a private key, you probably want to just use it.
pfx = GetKeyVaultCert().Result ?? throw etc;
I have an x509 certificate with a public and private key that is stored on a safenet usb token.
I have some data I want to sign. I need to use the public key of the certificate to verify the signature.
Ultimate code doing the signing with my own self signed certificate:
RSACryptoServiceProvider rsa1 = (RSACryptoServiceProvider)useCertificate.PrivateKey;
byte[] digitalSignature = rsa1.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
And the code to verify using the public key of the certificate:
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)useCertificate.PublicKey.Key;
Verified = rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), digitalSignature);
With the self signed certificate this works fine. The signature I get back is 256
Bytes.
With the token using this code to obtain the signature and then verify it, I get only 128 Byte signature and the verify fails:
CspParameters csp = new CspParameters(1, "SafeNet RSA CSP");
csp.Flags = CspProviderFlags.UseDefaultKeyContainer;
csp.KeyNumber = (int)KeyNumber.Signature;
RSACryptoServiceProvider rsa1 = new RSACryptoServiceProvider(csp);
Verify code same as above.
I note that the certificate I want to use is the default in the token. Why am I only getting a 128 Byte signature back instead of 256? I suspect that is why it won't verify.
Do I need some other parameters and settings in my csp?
Thanks
* Update based on comments *
It's clear that I am using 1024 bits when I specify the csp.keyNumber = (int)KeyNumber.Signature - but this is the only way the token actually returns anything. Even though the token key size is 2048 bits and the key specification is AT_KEYEXCHANGE. When I use the exchange keynumber which I think is actually correct, then when I try to compute a signature I am prompted to login, but then I get an exception "The parameter is invalid". So I need one of 2 things as far as I can see:
1 - how to use the public key to verify the signature using 1024 bits (without the token - we need to verify on a machine without the token).
or
2 - how to set whatever is incorrect so that we can get passed the exception -- which I think is the better idea.
Does anyone have any advice on what I can do about this exception or what might be causing it?
Full exception details below:
HResult = -2147024809
Message = The parameter is incorrect.
Stack Trace
at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
at System.Security.Cryptography.Utils.SignValue(SafeKeyHandle hKey, Int32 keyNumber, Int32 calgKey, Int32 calgHash, Byte[] hash, Int32 cbHash, ObjectHandleOnStack retSignature)
at System.Security.Cryptography.Utils.SignValue(SafeKeyHandle hKey, Int32 keyNumber, Int32 calgKey, Int32 calgHash, Byte[] hash)
at System.Security.Cryptography.RSACryptoServiceProvider.SignHash(Byte[] rgbHash, Int32 calgHash)
at System.Security.Cryptography.RSACryptoServiceProvider.SignHash(Byte[] rgbHash, String str)
at TE.Program.Main(String[] args) in z:\Work\compusolve\enctest\TE\TE\Program.cs:line 77
The answer to this is two fold. If you are using one of these devices, I found that in the registry under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\Defaults\Provider
There are 3 different providers. Each with identical settings for type and even image - the dll used. But selecting a different one, in my case Datakey RSP CSP, provided the 256 byte signature based on the 2048 bit key. You also have to ensure that the certificate you are using is the default certificate in the token. In my case there were two different certificates. I was verifying using one, but signing using another.
Complete source code for a test client is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
namespace TE
{
class Program
{
static void Main(string[] args)
{
try
{
// these variables should be changed to math your installation
// find CSP's in this windows registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\Defaults\Provider
string TokenCSPName = "Datakey RSA CSP";
string TokenCertificateName = "ACME Inc";
string NonTokenCertificateName = "SelfSigned";
string certLocation = "Token"; // change to something else to use self signed "Token" for token
// the certificate on the token should be installed into the local users certificate store
// tokens will not store or export the private key, only the public key
// find the certificate we want to use - there's no recovery if the certificate is not found
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.OpenExistingOnly);
X509Certificate2Collection certificates = store.Certificates;
X509Certificate2 certificate = new X509Certificate2();
X509Certificate2 useCertificate = new X509Certificate2();
if (certLocation == "Token")
{
for (int i = 0; i < certificates.Count; i++)
{
certificate = certificates[i];
string subj = certificate.Subject;
List<X509KeyUsageExtension> extensions = certificate.Extensions.OfType<X509KeyUsageExtension>().ToList();
if (certificate.GetNameInfo(X509NameType.SimpleName, false).ToString() == TokenCertificateName)
{
for (int j = 0; j < extensions.Count; j++)
{
if ((extensions[j].KeyUsages & X509KeyUsageFlags.DigitalSignature) == X509KeyUsageFlags.DigitalSignature)
{
useCertificate = certificate;
j = extensions.Count + 1;
}
}
}
}
} else
{
for (int i = 0; i < certificates.Count; i++)
{
certificate = certificates[i];
string subj = certificate.Subject;
List<X509KeyUsageExtension> extensions = certificate.Extensions.OfType<X509KeyUsageExtension>().ToList();
if (certificate.GetNameInfo(X509NameType.SimpleName, false).ToString() == NonTokenCertificateName)
useCertificate = certificate;
}
}
CspParameters csp = new CspParameters(1, TokenCSPName);
csp.Flags = CspProviderFlags.UseDefaultKeyContainer;
csp.KeyNumber = (int)KeyNumber.Exchange;
RSACryptoServiceProvider rsa1 = new RSACryptoServiceProvider(csp);
string SignatureString = "Data that is to be signed";
byte[] plainTextBytes = Encoding.ASCII.GetBytes(SignatureString);
bool Verified = false;
using (SHA1CryptoServiceProvider shaM = new SHA1CryptoServiceProvider())
{
// hash the data to be signed - you can use signData and avoid the hashing if you like
byte[] hash = shaM.ComputeHash(plainTextBytes);
// sign the hash
byte[] digitalSignature = rsa1.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
// check your signature size here - if not 256 bytes then you may not be using the proper
// crypto provider
// Verify the signature with the hash
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)useCertificate.PublicKey.Key;
Verified = rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), digitalSignature);
if (Verified)
{
Console.WriteLine("Signature Verified");
}
else
{
Console.WriteLine("Signature Failed Verification");
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
I have to challenge your assertion that it's actually the default key container key (you may have caused that one to be created the first time your code ran, since you didn't assert the UseExistingKey flag).
Assuming the certificate is in your cert store, run certutil -user -silent store my and find the certificate entry and check the Key Container value:
================ Certificate 11 ================
Serial Number: 0123456789abcdeffedcba9876543210
Issuer: CN=Intermediate Certificate Authority
NotBefore: 10/21/2016 7:26 AM
NotAfter: 10/21/2017 7:26 AM
Subject: CN=bartonjs
Non-root Certificate
Template:
Cert Hash(sha1): 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14
Key Container = le-Smartcard-987abcdf-6332-43-16531
Provider = Microsoft Base Smart Card Crypto Provider
If you copy/paste whatever value that is and use it as the key container name your signatures will probably start being the correct size.
(If your certificate is in the machine store instead of the user store, omit the -user option)
I am developing an encryption decryption software. I used RSA encryption to encypt my symmetric key.
I followed the code provided in Walkthrough: Creating a Cryptographic Application
My encryption and decryption done successfully in same machine. But when I tried to decrypt from other computer, an error: bad data is occurring.(It can be decrypted from same machine.)
I think the problem is on getting private key from keycontainer. How to get the private key generated in first machine in the second machine.
I googled a lot but everything in same machine.
Please help me, give me an idea to get private key in other machine.
public void GetPrivateKey()
{
string c;
cspp.KeyContainerName = keyName;
rsa = new RSACryptoServiceProvider(cspp);
rsa.PersistKeyInCsp = true;
if (rsa.PublicOnly == true)
c= "Key: " + cspp.KeyContainerName + " - Public Only";
else
c = "Key: " + cspp.KeyContainerName + " - Full Key Pair";
}
public string decryptkey(string at)
{
byte[] KeyEncrypted;
KeyEncrypted = File.ReadAllBytes(at);
//System.IO.File.ReadAllBytes(at);//for good
objr.GetPrivateKey();
byte[] KeyDecrypted = objr.rsa.Decrypt(KeyEncrypted, false);
string skey = GetString(KeyDecrypted);
return skey;
}
Bad data Error happens in this line,
byte[] KeyDecrypted = objr.rsa.Decrypt(KeyEncrypted, false);.
Please..
Use the RSACryptoServiceProvider.ToXmlString method to export the private key. You need to pass true to this method to export the private key. This will generate for you an XML document that contains the key parameters including the private parameters.
On the second machine, use RSACryptoServiceProvider.FromXmlString to import the private key into a RSACryptoServiceProvider instance.
However, for security reasons, I recommend that instead of doing this, generate the private key on one machine (the machine that will do the decryption part), and then use the RSACryptoServiceProvider.ToXmlString and pass false to it to just export the public key. On the other machine (that will do the encryption part), import the public key using the RSACryptoServiceProvider.FromXmlString method.
Using the public key alone, you can do the encryption part of the process.
It is only for decryption that you are required to have the private key.
Here is some sample code:
//Do this on one machine
RSACryptoServiceProvider rsa_machine1 = new RSACryptoServiceProvider(); //You might initialize this in a different way
var xml = rsa_machine1.ToXmlString(true); //or pass false to just export the public key
Now take the value of the xml variable to the other machine (maybe by saving it to a file and then manually copying that file to the second machine)
//This is done on the second machine
RSACryptoServiceProvider rsa_machine2 = new RSACryptoServiceProvider();
rsa_machine2.FromXmlString(xml);