Skip to content

Commit

Permalink
Merge pull request #5 from catcherwong/master
Browse files Browse the repository at this point in the history
add support for the length of MD5 hash result .
  • Loading branch information
myloveCc authored Oct 10, 2017
2 parents aa68e12 + 419dc8b commit 649f547
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 6 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 11 additions & 6 deletions src/NETCore.Encrypt/EncryptProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -423,30 +423,35 @@ public static RSAKey CreateRsaKey(RsaSize rsaSize = RsaSize.R2048)
#endregion

#region MD5

/// <summary>
/// MD5 hash
/// </summary>
/// <param name="srcString">The string to be encrypted</param>
/// <param name="srcString">The string to be encrypted.</param>
/// <param name="length">The length of hash result , default value is <see cref="MD5Length.L32"/>.</param>
/// <returns></returns>
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
/// <summary>
/// MD5 hash
/// HMACMD5 hash
/// </summary>
/// <param name="srcString">The string to be encrypted</param>
/// <param name="key">encrypte key</param>
Expand Down
8 changes: 8 additions & 0 deletions src/NETCore.Encrypt/Internal/MD5Length.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace NETCore.Encrypt
{
public enum MD5Length
{
L16 = 16,
L32 = 32
}
}
11 changes: 11 additions & 0 deletions test/NETCore.Encrypt.Tests/MD5_Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,16 @@ public void MD5_Error_Test()
{
Assert.Throws<ArgumentException>(() => 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());
}
}
}

0 comments on commit 649f547

Please sign in to comment.