ARTICLE AD BOX
The RSACryptoServiceProvider.Decrypt is failing on an internal call to Interop.Advapi32.CryptDecrypt. The internal error code is "31". The message is
System.Security.Cryptography**.CryptographicException: "A device attached to the system is not functioning
This library is calling an older C++ RSA implementation used by old equipment we still need.
static string? Decrypt(string pemString) { try { var cipherText = Convert.FromBase64String(@"..."); var cspParams = new CspParameters { ProviderType = 1, // PROV_RSA_FULL KeyContainerName = "Test" }; using (var rsaProvider = new RSACryptoServiceProvider(cspParams)) { rsaProvider.ImportFromPem(pemString); var maxChunkSize = (rsaProvider.KeySize / 8); using (var ms = new MemoryStream()) { for (var i = 0; i < cipherText.Length; i += maxChunkSize) { var chunkSize = Math.Min(maxChunkSize, cipherText.Length - i); var chunk = new byte[chunkSize]; Array.Copy(cipherText, i, chunk, 0, chunkSize); var decrypted = rsaProvider.Decrypt(chunk, false); // Error! ms.Write(decrypted, 0, decrypted.Length); } return Encoding.ASCII.GetString(ms.ToArray()); } } } catch (Exception ex) { Console.WriteLine("Exception decrypting file.", ex); } return null; }I have verified based on suggestions:
The PEM is good. OpenSSL says "RSA key ok". The array size is the only size allowed for decryption (keysize / 8). "false" for the fOAEP/padding parameter. My user (which the process runs as) has permissions to the key stores. The "sfc /scannow" found no issues. I've tried changing the KeyContainerName (can be corrupted, apparently). I've looked at a half dozen similar examples and seem to be following the normal guidelines. I tried adding flags, like CspProviderFlags.UseMachineKeyStore. RSACryptoServiceProvider is inside a "using" block. My code is NOT multi-threaded.Is there someone else on the system that the old Advapi32 code is attempting to communicate with?
1
