Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashAlgorithm.Create fails with PlatformNotSupportedException in C# ASP.NET Core 2

I have an ASP.Net MVC project which works fine when using HashAlgorithm, but I am trying to replicate this same project in ASP.NET Core 2 and I am getting the following error:

System.PlatformNotSupportedException HResult=0x80131539 Message=Operation is not supported on this platform. Source=System.Security.Cryptography.Primitives StackTrace: at System.Security.Cryptography.HashAlgorithm.Create(String hashName) at Hash.Program.EncodePassword(String pass, String salt)

My code:

public static string GeneratePassword(int saltlength) //length of salt
{
    const string chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
    var randNum = new Random();
    var passwordSalt = new char[saltlength];

    for (var i = 0; i <= saltlength - 1; i++) {
        passwordSalt[i] = chars[Convert.ToInt32((chars.Length) * randNum.NextDouble())];
    }
    return new string(passwordSalt);
}
public static string EncodePassword(string pass, string salt) //encrypt password
{
    byte[] bytes = Encoding.Unicode.GetBytes(pass);
    byte[] src = Encoding.Unicode.GetBytes(salt);
    byte[] dst = new byte[src.Length + bytes.Length];
    Buffer.BlockCopy(src, 0, dst, 0, src.Length);
    Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
    HashAlgorithm algorithm = HashAlgorithm.Create("MD5");
    if (algorithm != null) {
        byte[] inArray = algorithm.ComputeHash(dst);
        var encodedPassword = Convert.ToBase64String(inArray);
        return encodedPassword;
    }
    return pass;
}

Any suggestion on how to fix this error?

like image 280
Krishneil Avatar asked Jul 01 '26 09:07

Krishneil


2 Answers

There is a github issue for this problem which provides a workaround:

Workaround is to call (HashAlgorithm)CryptoConfig.CreateFromName(string), though calling CryptoConfig directly is generally discouraged.

like image 108
Lennart Stoop Avatar answered Jul 02 '26 21:07

Lennart Stoop


To create an MD5 hash object, use MD5.Create(). The only reason to use CryptoConfig or HashAlgorithm.Create(String) is when handling dynamic needs.

like image 44
bartonjs Avatar answered Jul 02 '26 22:07

bartonjs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!