|
| 1 | +using Microsoft.AspNetCore.Cryptography.KeyDerivation; |
| 2 | +using System; |
| 3 | +using System.Collections.Generic; |
| 4 | +using System.Security.Cryptography; |
| 5 | +using System.Text; |
| 6 | + |
| 7 | +namespace OpenPerpetuum.Core.Foundation.Security |
| 8 | +{ |
| 9 | + public static class Cryptography |
| 10 | + { |
| 11 | + /// <summary> |
| 12 | + /// Used for creating small readable crypto-tokens |
| 13 | + /// </summary> |
| 14 | + /// <param name="minimumLength"></param> |
| 15 | + /// <param name="tokenHashAlphabet"></param> |
| 16 | + /// <returns></returns> |
| 17 | + public static string CreateEncodedHashId(int minimumLength, string tokenHashAlphabet) |
| 18 | + { |
| 19 | + var seed = new Random(BitConverter.ToInt32(CreateRandomBytes(4), 0)).Next(0, int.MaxValue); |
| 20 | + var salt = CreateRandomBytes(32); |
| 21 | + |
| 22 | + string saltString = Convert.ToBase64String(salt); |
| 23 | + |
| 24 | + var hashId = new HashidsNet.Hashids(salt: saltString, minHashLength: minimumLength, alphabet: tokenHashAlphabet); |
| 25 | + var hash = hashId.Encode(seed); |
| 26 | + |
| 27 | + return hash; |
| 28 | + } |
| 29 | + public static byte[] CreatePasswordForStorage(string password) |
| 30 | + { |
| 31 | + byte[] salt = CreateRandomBytes(32); |
| 32 | + byte[] encryptedPassword = CreatePasswordForStorage(password, salt); |
| 33 | + |
| 34 | + return encryptedPassword; |
| 35 | + } |
| 36 | + |
| 37 | + public static byte[] CreatePasswordForStorage(string password, byte[] salt) |
| 38 | + { |
| 39 | + byte[] hashedPassword = HashPassword(password, salt); |
| 40 | + byte[] encryptedPassword = ReadyPasswordForStorage(salt, hashedPassword); |
| 41 | + |
| 42 | + return encryptedPassword; |
| 43 | + } |
| 44 | + |
| 45 | + public static byte[] CreateRandomBytes(int numberOfBytes = 32) |
| 46 | + { |
| 47 | + var randomGenerator = RandomNumberGenerator.Create(); |
| 48 | + |
| 49 | + byte[] cryptoBytes = new byte[numberOfBytes]; |
| 50 | + |
| 51 | + randomGenerator.GetBytes(cryptoBytes); |
| 52 | + |
| 53 | + return cryptoBytes; |
| 54 | + } |
| 55 | + |
| 56 | + public static byte[] HashPassword(string password, byte[] salt, int numberOfIterations = 50000) |
| 57 | + { |
| 58 | + byte[] hashedPassword = |
| 59 | + KeyDerivation.Pbkdf2( |
| 60 | + password, |
| 61 | + salt, |
| 62 | + KeyDerivationPrf.HMACSHA512, |
| 63 | + numberOfIterations, |
| 64 | + 32); |
| 65 | + |
| 66 | + return hashedPassword; |
| 67 | + } |
| 68 | + |
| 69 | + public static byte[] ReadyPasswordForStorage(byte[] salt, byte[] hashedPassword) |
| 70 | + { |
| 71 | + var encryptedPassword = new byte[hashedPassword.Length + salt.Length]; |
| 72 | + |
| 73 | + Array.Copy(salt, encryptedPassword, salt.Length); |
| 74 | + Array.Copy(hashedPassword, 0, encryptedPassword, salt.Length, hashedPassword.Length); |
| 75 | + |
| 76 | + return encryptedPassword; |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments