aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Core/Cryptography/BasicHashGenerator.cs
blob: 8715d4abe7cc62931287a8feb6fd9b917f5cb919 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Tango.Core.Cryptography
{
    /// <summary>
    /// Represents a hashing algorithm engine for one-way password encryption.
    /// </summary>
    /// <seealso cref="Tango.Core.Cryptography.IEncryptor" />
    public class BasicHashGenerator : IHashGenerator
    {
        /// <summary>
        /// Encrypts the specified text using the static salt key.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns></returns>
        public string Encrypt(string text)
        {
            return Encrypt(text, "twine-solutions9");
        }

        /// <summary>
        /// Encrypts the specified text using the specified salt.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="salt">The key.</param>
        /// <returns></returns>
        public string Encrypt(string text, string salt)
        {
            if (salt.Length < 16)
            {
                salt = salt.PadRight(16);
            }

            salt = salt.Substring(0, 16);

            byte[] saltBytes = Encoding.ASCII.GetBytes(salt);

            var pbkdf2 = new Rfc2898DeriveBytes(text, saltBytes, 10000);
            byte[] hash = pbkdf2.GetBytes(20);

            byte[] hashBytes = new byte[36];
            Array.Copy(saltBytes, 0, hashBytes, 0, 16);
            Array.Copy(hash, 0, hashBytes, 16, 20);

            return Convert.ToBase64String(hashBytes);
        }

        /// <summary>
        /// Validates the specified text against the specified hash.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="hash"></param>
        public bool Validate(string text, string hash)
        {
            byte[] hashBytes = Convert.FromBase64String(hash);

            byte[] salt = new byte[16];
            Array.Copy(hashBytes, 0, salt, 0, 16);

            var pbkdf2 = new Rfc2898DeriveBytes(text, salt, 10000);
            byte[] h = pbkdf2.GetBytes(20);
            for (int i = 0; i < 20; i++)
            {
                if (hashBytes[i + 16] != h[i])
                {
                    return false;
                }
            }

            return true;
        }
    }
}