encryption.net-3.5cryptographicexception

Error codes for CryptographicExceptions?


I'm trying to map different CryptographicExceptions to custom exceptions and messages. For example, "Object already exists" ==> "Not enough permissions to access an existing RSA key container". However, when I examine CryptographicException class, I don't find any error code collection like other exception types have. I'm running on 3.5, so HResult is not available either. Finally, I cannot rely on the message, since it can be localized. Any other ideas?


Solution

  • public Exception GetMappedCryptographicException(CryptographicException e)
    {
        uint hresult = (uint)Marshal.GetHRForException(e);
    
        switch (hresult)
        {
            case 0x8009000F;  // OBJECT_ALREADY_EXISTS
                return new Exception(e, "Not enough permissions to access RSA key container.");
            default:
                return new Exception(e, "Unexpected cryptographic exception occurred.");
        }
    }