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.