# 一种密码加密存储方案：加盐哈希

• 什么是盐？
• 什么是哈希算法？
• 加密与校验过程。
• C#实现。

#### 什么是盐？

 In cryptography, a salt is random data that is used as an additional input to a one-way function that hashes data, a password or passphrase. -- From Wiki.


#### 什么是哈希算法？

A cryptographic hash function (CHF) is a hash function that is suitable for use in cryptography. It is a mathematical algorithm that maps data of arbitrary size (often called the "message") to a bit string of a fixed size (the "hash value", "hash", or "message digest") and is a one-way function, that is, a function which is practically infeasible to invert. -- From Wiki.


#### 加密与校验过程

C#实现

 1         ///
2         /// 生成盐
3         ///
4         ///
5         public static byte[] GetSalt()
6         {
7             //Buffer storage.
8             var salt = new byte[8];
9             using (var provider = new RNGCryptoServiceProvider())
10             {
11                 provider.GetBytes(salt);
12             }
13             return salt;
14         }


 1         ///
2         /// 合并盐与明文
3         ///
4         ///
5         ///
6         ///
7         private static byte[] CombineByteArray(byte[] byte1, byte[] byte2)
8         {
9             var ret = new byte[byte1.Length + byte2.Length];
10             Array.Copy(byte1, 0, ret, 0, byte1.Length);
11             Array.Copy(byte2, 0, ret, byte1.Length, byte2.Length);
12             return ret;
13         }


 1         ///
2         /// Hash Salted input and salt
3         ///
4         /// input
5         /// salt
6         /// return 32 bytes hashed values
7         public static byte[] HashSalted256(string input, byte[] salt)
8         {
9             var bytes = Encoding.Unicode.GetBytes(input);
10             byte[] hashSaltedValue = null;
11             using (var sha256 = new SHA256CryptoServiceProvider())
12             {
13                 var saltedInput = CombineByteArray(bytes, salt);
14                 hashSaltedValue = sha256.ComputeHash(saltedInput);
15             }
16             return hashSaltedValue;
17         }