diff --git a/README.md b/README.md index 5eec056..aef3fd6 100644 --- a/README.md +++ b/README.md @@ -139,6 +139,13 @@ Install-Package NETCore.Encrypt -Version 2.0.2 ``` + ```csharp + + var srcString = "Md5 hash"; + var hashed = EncryptProvider.Md5(srcString, MD5Length.L16); + + ``` + ## SHA - #### SHA1 diff --git a/src/NETCore.Encrypt/EncryptProvider.cs b/src/NETCore.Encrypt/EncryptProvider.cs index efb45f1..d192759 100644 --- a/src/NETCore.Encrypt/EncryptProvider.cs +++ b/src/NETCore.Encrypt/EncryptProvider.cs @@ -423,30 +423,35 @@ public static RSAKey CreateRsaKey(RsaSize rsaSize = RsaSize.R2048) #endregion #region MD5 - /// /// MD5 hash /// - /// The string to be encrypted + /// The string to be encrypted. + /// The length of hash result , default value is . /// - public static string Md5(string srcString) + public static string Md5(string srcString, MD5Length length = MD5Length.L32) { Check.Argument.IsNotEmpty(srcString, nameof(srcString)); + string str_md5_out = string.Empty; using (MD5 md5 = MD5.Create()) { byte[] bytes_md5_in = Encoding.UTF8.GetBytes(srcString); byte[] bytes_md5_out = md5.ComputeHash(bytes_md5_in); - string str_md5_out = BitConverter.ToString(bytes_md5_out); + + str_md5_out = length == MD5Length.L32 + ? BitConverter.ToString(bytes_md5_out) + : BitConverter.ToString(bytes_md5_out, 4, 8); + str_md5_out = str_md5_out.Replace("-", ""); return str_md5_out; } - } + } #endregion #region HMACMD5 /// - /// MD5 hash + /// HMACMD5 hash /// /// The string to be encrypted /// encrypte key diff --git a/src/NETCore.Encrypt/Internal/MD5Length.cs b/src/NETCore.Encrypt/Internal/MD5Length.cs new file mode 100644 index 0000000..4c6c31c --- /dev/null +++ b/src/NETCore.Encrypt/Internal/MD5Length.cs @@ -0,0 +1,8 @@ +namespace NETCore.Encrypt +{ + public enum MD5Length + { + L16 = 16, + L32 = 32 + } +} diff --git a/test/NETCore.Encrypt.Tests/MD5_Tests.cs b/test/NETCore.Encrypt.Tests/MD5_Tests.cs index 5fc6ac3..d62f538 100644 --- a/test/NETCore.Encrypt.Tests/MD5_Tests.cs +++ b/test/NETCore.Encrypt.Tests/MD5_Tests.cs @@ -25,5 +25,16 @@ public void MD5_Error_Test() { Assert.Throws(() => EncryptProvider.Md5(string.Empty)); } + + [Fact(DisplayName = "MD5 with length success test")] + public void MD5_With_Length_Success_Test() + { + var srcString = "Md5 test"; + + var hashed = EncryptProvider.Md5(srcString, MD5Length.L16); + + Assert.NotEmpty(hashed); + Assert.Equal("69c6ecadb32f5492", hashed.ToLower()); + } } }