Harshith R
Harshith R

Reputation: 448

Getting Exception "Key not valid for use in specified state" while decrypting a file

I am generating a certificate and encrypting that certifiacte as a bin file to the local disk. I am doing this using the following powershell code:

$bytes = $CertificateResponse.ToCharArray() | % {[byte] $_}
[Byte[]]$entropy = 4,17,9,88,236,1688,1486,41,182,16,72,93,2,188,2,23

# Encrypt the byte array.
$encryptedBytes = [System.Security.Cryptography.ProtectedData]::Protect(
        $bytes, 
        $entropy, 
        [System.Security.Cryptography.DataProtectionScope]::LocalMachine)

$encryptedBytes | Set-Content C:\certificate\xxx.bin -Encoding Byte

Later the same binary file is kept on other machine, and i am trying to read and decrypt the file as follows(using c#):

 try
            {
                this.EntropyKey = new byte[] { 4,17,9,88,236,1688,1486,41,182,16,72,93,2,188,2,23};
                var data = File.ReadAllBytes(Path.Combine(localPath, "xxx.bin"));
                var decryptedData = ProtectedData.Unprotect(data, this.EntropyKey, DataProtectionScope.LocalMachine);
                this.Certificate = new X509Certificate(decryptedData);
                return Task.CompletedTask;
            }
            catch (Exception ex)
            {
                throw new NotImplementedException();
            }

When I run the code I am getting Exception as "Key not valid for use in specified state" at the line where i am trying to decrypt. It works fine if I try to decrypt using powershell command. Any help would be much appreciated. Note : I have given read permission to the file.

Upvotes: 2

Views: 2951

Answers (1)

Crypt32
Crypt32

Reputation: 13954

ProtectedData uses DPAPI to protect data. This means that you can encrypt/decrypt data on same machine, but cannot encrypt on one machine and decrypt on another machine, because each machine has its own DPAPI master key. If you need to work with encrypted data on different machines, you cannot use DPAPI. Instead, you have to use other means to encrypt and decrypt data. For example, you can use AES class.

Upvotes: 7

Related Questions