123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- using Microsoft.AspNetCore.Cryptography.KeyDerivation;
- using Microsoft.IdentityModel.Tokens;
- using System;
- using System.Collections.Generic;
- using System.IdentityModel.Tokens.Jwt;
- using System.Security.Claims;
- using System.Security.Cryptography;
- using System.Text;
- namespace TEAMModelOS.SDK.Extension
- {
- public class Utils
- {
- private static RNGCryptoServiceProvider _random = new RNGCryptoServiceProvider();
- public static string HashedPassword(string password, string salt)
- {
- byte[] hashBytes = KeyDerivation.Pbkdf2(
- password: password,
- salt: Encoding.UTF8.GetBytes(salt), //SHA1鹽(8-20字節),SHA256(32字節)
- prf: KeyDerivationPrf.HMACSHA1,
- iterationCount: 10000, //hash次數,越多次代表破解難度變高,但效能會差點
- numBytesRequested: 256 / 8 //指定得出結果長度
- );
- string hashText = BitConverter.ToString(hashBytes).Replace("-", string.Empty);
- return hashText;
- }
- /// <summary>
- /// 建立真隨機字串(CSPRNG),適用密碼、鹽
- /// </summary>
- /// <param name="stringLength">長度</param>
- /// <param name="key">要限制的字元串(長度需大於等於8),如果為null或者小於8,預設為"abcdefghijklmnopqrstuvwxyz1234567890"</param>
- /// <returns></returns>
- public static string CreatSaltString(int stringLength, string key = null)
- {
- ReadOnlySpan<char> span;
- if (key == null || key.Length < 8)
- span = "abcdefghijklmnopqrstuvwxyz1234567890";
- else
- span = key.AsSpan();
- int length = span.Length;
- StringBuilder randomString = new StringBuilder(length);
- for (int i = 0; i < stringLength; ++i)
- {
- randomString.Append(span[SetRandomSeeds(length)]);
- }
- return randomString.ToString();
- }
- /// <summary>
- /// 建立真隨機整數數字(CSPRNG),適用亂數、隨機編號
- /// </summary>
- /// <param name="max">最大值</param>
- public static int CreatSaltInt(int max)
- {
- var bytes = new byte[4];
- _random.GetBytes(bytes);
- int value = BitConverter.ToInt32(bytes, 0);
- value = value % (max + 1);
- if (value < 0) value = -value;
- return value;
- }
- /// <summary>
- /// 建立真隨機整數數字(CSPRNG),適用亂數、隨機編號
- /// </summary>
- /// <param name="min">最小值</param>
- /// <param name="max">最大值</param>
- public static int CreatSaltInt(int min, int max)
- {
- int value = CreatSaltInt(max - min) + min;
- return value;
- }
- public static Dictionary<string, string> ParseConnectionString(string connectionString)
- {
- var d = new Dictionary<string, string>();
- foreach (var item in connectionString.Split(';',StringSplitOptions.RemoveEmptyEntries))
- {
- var a = item.IndexOf('=');
- d.Add(item.Substring(0, a), item.Substring(a + 1));
- }
- return d;
- }
- private static int SetRandomSeeds(int length)
- {
- decimal maxValue = (decimal)long.MaxValue;
- byte[] array = new byte[8];
- _random.GetBytes(array);
- return (int)(Math.Abs(BitConverter.ToInt64(array, 0)) / maxValue * length);
- }
- }
- }
|