Rob.Core
Rob.Core

Reputation: 21

Use md5 to encrypt the password in asp.net .core

I would like to change the password encryption method in asp.net .core, I would like to use md5 to encrypt the password without losing all the advantages offered by the framework.

I have already created the methods of crypt and verification of the password but, in the application I have lost all the controls of authorization in the controllers and of verification of the authentication of the user, can someone help me?

Upvotes: 2

Views: 16441

Answers (2)

Tropin Alexey
Tropin Alexey

Reputation: 766

Same as @Hamid but with extension

public static class StringExtension
{
    public static string GetMd5Hash(this string input)
    {
        using MD5 md5Hash = MD5.Create();
        byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
        StringBuilder sBuilder = new StringBuilder();

        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }
        return sBuilder.ToString();
    }
}

So, you can use it like var encodedPassword = password.GetMd5Hash();

  • This kind of using is availible from above c# version 7.3

Upvotes: 2

Hamid
Hamid

Reputation: 908

MD5 is a hash algorithm!

Hash algorithms (like SHA256, SHA512, MD5) map binary strings of an arbitrary length to small binary strings of a fixed length.

Encryption is the method by which plaintext or any other type of data is converted from a readable form to an encoded version that can only be decoded by another entity if they have access to a decryption key.

Use MD5 only for compatibility with legacy applications and data, But still if you want to hash a plain text using md5 u can use below sample code:

using System;
using System.Text;
using System.Security.Cryptography;

public class Program
{
    public static void Main()
    {
         string source = "Hello World!";
            using (MD5 md5Hash = MD5.Create())
            {
                string hash = GetMd5Hash(md5Hash, source);
                Console.WriteLine("The MD5 hash of " + source + " is: " + hash + ".");
            }
    }
      static string GetMd5Hash(MD5 md5Hash, string input)
        {
            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }
}

For complete understanding about this topic u can follow below link that I copy it from Microsoft docs: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.md5?view=netframework-4.8

Upvotes: 6

Related Questions