Dov
Dov

Reputation: 16186

Read an encrypted value across machines

I'm trying to write out encrypted data in such a way that the same user account (on a domain) can read the data from a different machine than the one that wrote it - but only that user can. It looks like the System.Security.Cryptography.ProtectedData class doesn't work that way. It's a command line tool.

var encryptedData = ProtectedData.Protect(data, null, DataProtectionScope.CurrentUser);

Is there another way to encrypt data with .Net that will allow such access?

Upvotes: 1

Views: 779

Answers (1)

Igor
Igor

Reputation: 62298

You can use System.Web.Security.MachineKey but you have to make sure that the applications have the same configuration in their respective app.config/web.config files for the machineKey section. It can be found here in the configuration:

<configuration>
  <system.web>
    <machineKey decryption="[type]" decryptionKey="[value]" validation="[value]" validationKey="value" />

There are plenty of tools you can use to generate the values including IIS if you have an asp.net site configured.

Example with an actual key I generated from IIS in section ASP.NET => Machine Key.

static void Main(string[] args)
{
    var encrypted = Encrypt("this will be encrypted");
    Console.WriteLine("Encrypted base64: " + encrypted);
    Console.WriteLine();


    var unencrypted = Unencrypt(encrypted);
    Console.WriteLine("Decrypted: " + unencrypted);

    Console.ReadLine();
}

static string Encrypt(string valueToEncrypt)
{
    var toEncrypt = System.Text.Encoding.UTF8.GetBytes(valueToEncrypt);
    var encryptedData = System.Web.Security.MachineKey.Protect(toEncrypt, null);
    var result = Convert.ToBase64String(encryptedData);
    return result;
}

static string Unencrypt(string value)
{
    var toUnencrypt = Convert.FromBase64String(value);
    var deencryptedData = System.Web.Security.MachineKey.Unprotect(toUnencrypt, null);
    var originalValue = System.Text.Encoding.UTF8.GetString(deencryptedData);
    return originalValue;
}

Upvotes: 1

Related Questions