Skip to content

Commit 649f547

Browse files
authored
Merge pull request #5 from catcherwong/master
add support for the length of MD5 hash result .
2 parents aa68e12 + 419dc8b commit 649f547

File tree

4 files changed

+37
-6
lines changed

4 files changed

+37
-6
lines changed

README.md

+7
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,13 @@ Install-Package NETCore.Encrypt -Version 2.0.2
139139

140140
```
141141

142+
```csharp
143+
144+
var srcString = "Md5 hash";
145+
var hashed = EncryptProvider.Md5(srcString, MD5Length.L16);
146+
147+
```
148+
142149
## SHA
143150

144151
- #### SHA1

src/NETCore.Encrypt/EncryptProvider.cs

+11-6
Original file line numberDiff line numberDiff line change
@@ -423,30 +423,35 @@ public static RSAKey CreateRsaKey(RsaSize rsaSize = RsaSize.R2048)
423423
#endregion
424424

425425
#region MD5
426-
427426
/// <summary>
428427
/// MD5 hash
429428
/// </summary>
430-
/// <param name="srcString">The string to be encrypted</param>
429+
/// <param name="srcString">The string to be encrypted.</param>
430+
/// <param name="length">The length of hash result , default value is <see cref="MD5Length.L32"/>.</param>
431431
/// <returns></returns>
432-
public static string Md5(string srcString)
432+
public static string Md5(string srcString, MD5Length length = MD5Length.L32)
433433
{
434434
Check.Argument.IsNotEmpty(srcString, nameof(srcString));
435435

436+
string str_md5_out = string.Empty;
436437
using (MD5 md5 = MD5.Create())
437438
{
438439
byte[] bytes_md5_in = Encoding.UTF8.GetBytes(srcString);
439440
byte[] bytes_md5_out = md5.ComputeHash(bytes_md5_in);
440-
string str_md5_out = BitConverter.ToString(bytes_md5_out);
441+
442+
str_md5_out = length == MD5Length.L32
443+
? BitConverter.ToString(bytes_md5_out)
444+
: BitConverter.ToString(bytes_md5_out, 4, 8);
445+
441446
str_md5_out = str_md5_out.Replace("-", "");
442447
return str_md5_out;
443448
}
444-
}
449+
}
445450
#endregion
446451

447452
#region HMACMD5
448453
/// <summary>
449-
/// MD5 hash
454+
/// HMACMD5 hash
450455
/// </summary>
451456
/// <param name="srcString">The string to be encrypted</param>
452457
/// <param name="key">encrypte key</param>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
namespace NETCore.Encrypt
2+
{
3+
public enum MD5Length
4+
{
5+
L16 = 16,
6+
L32 = 32
7+
}
8+
}

test/NETCore.Encrypt.Tests/MD5_Tests.cs

+11
Original file line numberDiff line numberDiff line change
@@ -25,5 +25,16 @@ public void MD5_Error_Test()
2525
{
2626
Assert.Throws<ArgumentException>(() => EncryptProvider.Md5(string.Empty));
2727
}
28+
29+
[Fact(DisplayName = "MD5 with length success test")]
30+
public void MD5_With_Length_Success_Test()
31+
{
32+
var srcString = "Md5 test";
33+
34+
var hashed = EncryptProvider.Md5(srcString, MD5Length.L16);
35+
36+
Assert.NotEmpty(hashed);
37+
Assert.Equal("69c6ecadb32f5492", hashed.ToLower());
38+
}
2839
}
2940
}

0 commit comments

Comments
 (0)