Skip to content

Commit

Permalink
Merge pull request #47 from SergeyGulik/md5_not_thread_safe
Browse files Browse the repository at this point in the history
MD5 implementation is not thread safe
  • Loading branch information
PatrickRitchie authored May 6, 2023
2 parents b9a3c8b + bab6d4a commit b258b42
Showing 1 changed file with 35 additions and 8 deletions.
43 changes: 35 additions & 8 deletions src/MTConnect.NET-Common/Extensions/StringFunctions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,38 @@ namespace MTConnect
{
public static class StringFunctions
{
private static readonly Random _random = new Random();
private static readonly Encoding _utf8 = Encoding.UTF8;
private static MD5 _md5 = MD5.Create();

[ThreadStatic]
private static MD5 _md5;

[ThreadStatic]
private static Random _random;

private static MD5 MD5Algorithm
{
get
{
if (_md5 == null)
{
_md5 = MD5.Create();
}
return _md5;
}
}

private static Random Random
{
get
{
if (_random == null)
{
_random = new Random();
}

return _random;
}
}

public static string ToPascalCase(this string s)
{
Expand Down Expand Up @@ -237,7 +265,7 @@ public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[_random.Next(s.Length)]).ToArray());
.Select(s => s[Random.Next(s.Length)]).ToArray());
}

public static DateTime ToDateTime(this string s)
Expand All @@ -254,8 +282,7 @@ public static string ToMD5Hash(this string s)
{
try
{
if (_md5 == null) _md5 = MD5.Create();
var hash = _md5.ComputeHash(_utf8.GetBytes(s));
var hash = MD5Algorithm.ComputeHash(_utf8.GetBytes(s));
return string.Concat(hash.Select(b => b.ToString("x2")));
}
catch { }
Expand All @@ -269,7 +296,7 @@ public static string ToMD5Hash(this byte[] bytes)
{
try
{
var hash = _md5.ComputeHash(bytes);
var hash = MD5Algorithm.ComputeHash(bytes);
return string.Concat(hash.Select(b => b.ToString("x2")));
}
catch { }
Expand All @@ -296,7 +323,7 @@ public static byte[] ToMD5HashBytes(this string s)
{
try
{
return _md5.ComputeHash(_utf8.GetBytes(s));
return MD5Algorithm.ComputeHash(_utf8.GetBytes(s));
}
catch { }

Expand All @@ -309,7 +336,7 @@ public static byte[] ToMD5HashBytes(this byte[] bytes)
{
try
{
return _md5.ComputeHash(bytes);
return MD5Algorithm.ComputeHash(bytes);
}
catch { }
}
Expand Down

0 comments on commit b258b42

Please sign in to comment.