Skip to content

Commit

Permalink
Merge pull request #170 from InCerryGit/master
Browse files Browse the repository at this point in the history
fix potential thread safety issues.
  • Loading branch information
kklldog committed Mar 2, 2024
2 parents 9d3f9c4 + da2d09b commit e94c9e9
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/AgileConfig.Server.Common/Encrypt.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
using System;
using System.Security.Cryptography;
using System.Text;
using System.Threading;

namespace AgileConfig.Server.Common
{
public static class Encrypt
{
private static readonly MD5 Md5Instance = MD5.Create();
private static readonly ThreadLocal<MD5> Md5Instance = new ThreadLocal<MD5>(MD5.Create);
public static string Md5(string txt)
{
var inputBytes = Encoding.ASCII.GetBytes(txt);
var hashBytes = Md5Instance.ComputeHash(inputBytes);
var hashBytes = Md5Instance.Value.ComputeHash(inputBytes);
return Convert.ToHexString(hashBytes);
}
}
Expand Down
28 changes: 28 additions & 0 deletions test/AgileConfig.Server.CommonTests/EncryptTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AgileConfig.Server.Common.Tests;

[TestClass]
public class EncryptTests
{
private const string Origin = "123456";
private const string Expected = "E10ADC3949BA59ABBE56E057F20F883E";

[TestMethod]
public void Md5Test()
{
var result = Encrypt.Md5(Origin);
Assert.AreEqual(Expected, result);
}

[TestMethod]
public void ParallelCallTest()
{
Parallel.For(0, 1000, _ =>
{
var result = Encrypt.Md5(Origin);
Assert.AreEqual(Expected, result);
});
}
}

0 comments on commit e94c9e9

Please sign in to comment.