My project required key recovery features where the system admin can upload RSA Key container to restore it in the event for disaster recovery
Current implementation is when admin upload the backup RSA Key container file, the app will move it to RSA Key container folder located at C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys
I tried to recover the key container from server into my local machine
Key container from server :
a953858192ce652ca077837fd55e8ea2_06454689-ae14-440b-aa53-c2eaac321be6
the bold part is Server Machine ID
When the RSACryptoServiceProvider tried to access the container, it will create a new container because the key name is not contain my local machine ID, made the decryption of encrypted data from server doesn't work.
I tried to rename the machine ID to my local machine ID
a953858192ce652ca077837fd55e8ea2_fbf0b515-e8c9-450d-bc0c-4bcb55cbd342
and the RSACryptoService throw error :
"Key not valid for use in specified state."
Code implementation in C# :
try{
// Create the CspParameters object and set the key container name used to store the RSA key pair.
var parameters = new CspParameters {KeyContainerName = containerName, Flags = UseMachineKeyStore};
// Create a new instance of RSACryptoServiceProvider that accesses
// the key container Key Container Name.
using var rsaCryptoServiceProvider = new RSACryptoServiceProvider(parameters); // error thrown "Key not valid for use in specified state."
try
{
var keyContainerBlob = rsaCryptoServiceProvider.ExportCspBlob(true);
using (var rsa = System.Security.Cryptography.RSA.Create())
{
rsa.KeySize = CryptoCommonHeap.RSAEncryptionKeySize;
rsaCryptoServiceProvider.ImportCspBlob(keyContainerBlob);
var privateKeyParameters = rsaCryptoServiceProvider.ExportParameters(true).ToPrivateKeyParameters();
var privateKeyParametersJson = JsonConvert.SerializeObject(privateKeyParameters);
PrivateKeyParametersJson = privateKeyParametersJson;
}
}
finally
{
// Setting This If Do Not Want To Store The File Persistently
//rsaCryptoServiceProvider.PersistKeyInCsp = false;
}
}
catch (Exception exception)
{
LogErrorToDatabase(ModuleName, "GenerateKeyAndSaveInKeyStore", exception);
}
I hope someone can enlighten me a correct way to restore RSA key container from another machine..