Thursday, 22 October 2015

[Solution] Exception has been thrown by the target of an invocation c#

Error: Exception has been thrown by the target of an invocation c#

If you are getiing this error message, hope you are using MD5 hash in side your code on an environment where FIPS is enabled.
You can find these security settings in server's local security settings. What is fips and how its affect your application
, to know such details you may refer [ FIPS error & solution ].

So if we talk about the current Error you may Use SHA1 hash insted of using MD5. Have a look on bellow code.
This code also describe how to calulate MD5 or SHA1 hash in c#.
Code 2 is final solution to resolve the issue.

Code 1: Cause of error
 public string CalculateMD5Hash(string input)
     // step 1, calculate MD5 hash from input
     MD5 md5 = System.Security.Cryptography.MD5.Create();
     byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
     byte[] hash = md5.ComputeHash(inputBytes);

     // step 2, convert byte array to hex string
     StringBuilder sb = new StringBuilder();
     for (int i = 0; i < hash.Length; i++)
     return sb.ToString();

Code 2: Solution
public string CalculateSha1Hash(string input)
// step 1, calculate SHA1 hash from input
    using (SHA1Managed sha1 = new SHA1Managed())
        var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));
        var sb = new StringBuilder(hash.Length * 2);

        foreach (byte b in hash)
            // can be "x2" if you want lowercase

        return sb.ToString();