Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MD5 implementation is not thread safe #47

Merged
merged 1 commit into from
May 6, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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