tuitio/IdentityServer.Application/Services/HashingService.cs

60 lines
2.1 KiB
C#

using IdentityServer.Application.Services.Abstractions;
using System;
using System.Security.Authentication;
using System.Security.Cryptography;
namespace IdentityServer.Application.Services
{
internal class HashingService : IHashingService
{
public string HashMd5(string text) => Hash(text, HashAlgorithmType.Md5);
public string HashSha1(string text) => Hash(text, HashAlgorithmType.Sha1);
public string HashSha256(string text) => Hash(text, HashAlgorithmType.Sha256);
public string HashSha384(string text) => Hash(text, HashAlgorithmType.Sha384);
public string HashSha512(string text) => Hash(text, HashAlgorithmType.Sha512);
private string Hash(string text, HashAlgorithmType algorithm)
{
if (string.IsNullOrEmpty(text))
throw new ArgumentException("Cannot hash null value.", nameof(text));
using (var sha = GetHashAlgorithm(algorithm))
{
byte[] textData = System.Text.Encoding.UTF8.GetBytes(text);
byte[] hash = sha.ComputeHash(textData);
var str = BitConverter.ToString(hash);
return str.Replace("-", String.Empty);
}
}
private HashAlgorithm GetHashAlgorithm(HashAlgorithmType algorithmType)
{
switch (algorithmType)
{
case HashAlgorithmType.None:
throw new ArgumentException("Do not use this method with HashAlgorithmType.None.", nameof(algorithmType));
case HashAlgorithmType.Md5:
return MD5.Create();
case HashAlgorithmType.Sha1:
return SHA1.Create();
case HashAlgorithmType.Sha256:
return SHA256.Create();
case HashAlgorithmType.Sha384:
return SHA384.Create();
case HashAlgorithmType.Sha512:
return SHA512.Create();
default:
throw new NotImplementedException($"HashAlgorithmType {algorithmType} is not implemented.");
}
}
}
}