2017-05-08 21:06:17 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Security.Cryptography;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
2017-07-22 19:27:41 +00:00
|
|
|
|
namespace Glove {
|
2017-05-08 21:06:17 +00:00
|
|
|
|
public static class CryptoExtensions {
|
2017-05-20 23:33:39 +00:00
|
|
|
|
public static byte[] SHA1(this string str)
|
|
|
|
|
=> Encoding.UTF8.GetBytes(str).SHA1();
|
2017-05-08 21:06:17 +00:00
|
|
|
|
|
2017-05-09 12:22:04 +00:00
|
|
|
|
public static byte[] SHA1(this byte[] bytes) {
|
2017-05-08 21:06:17 +00:00
|
|
|
|
using(var hasher = new SHA1CryptoServiceProvider()) {
|
2017-05-09 12:22:04 +00:00
|
|
|
|
return hasher.ComputeHash(bytes);
|
2017-05-08 21:06:17 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-05-20 23:33:39 +00:00
|
|
|
|
public static byte[] MD5(this string str)
|
|
|
|
|
=> Encoding.UTF8.GetBytes(str).MD5();
|
2017-05-09 12:22:04 +00:00
|
|
|
|
|
|
|
|
|
public static byte[] MD5(this byte[] bytes) {
|
2017-05-08 21:06:17 +00:00
|
|
|
|
using(var hasher = new MD5CryptoServiceProvider()) {
|
2017-05-09 12:22:04 +00:00
|
|
|
|
return hasher.ComputeHash(bytes);
|
2017-05-08 21:06:17 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2017-08-23 21:00:44 +00:00
|
|
|
|
|
|
|
|
|
private const int HashIterations = 3000;
|
|
|
|
|
|
|
|
|
|
public static byte[] HashPassword(this string pwd) {
|
|
|
|
|
byte[] salt, hash = new byte[36];
|
|
|
|
|
RNG.NextBytes(salt = new byte[16]);
|
|
|
|
|
|
|
|
|
|
using(var hasher = new Rfc2898DeriveBytes(pwd, salt, HashIterations)) {
|
|
|
|
|
byte[] rawHash = hasher.GetBytes(20);
|
|
|
|
|
Array.Copy(salt, 0, hash, 0, 16);
|
|
|
|
|
Array.Copy(rawHash, 0, hash, 16, 20);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return hash;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static bool CheckPassword(this string pwd, byte[] hash) {
|
|
|
|
|
byte[] salt = hash.Take(16).ToArray();
|
|
|
|
|
|
|
|
|
|
using(var hasher = new Rfc2898DeriveBytes(pwd, salt, HashIterations)) {
|
|
|
|
|
byte[] phash = hasher.GetBytes(20);
|
|
|
|
|
return hash.Skip(16).SequenceEqual(phash);
|
|
|
|
|
}
|
|
|
|
|
}
|
2017-05-08 21:06:17 +00:00
|
|
|
|
}
|
|
|
|
|
}
|