CGC_Codes

Create Password Hash

Mar 13th, 2017
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.65 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Security.Cryptography;
  6. using System.ComponentModel;
  7.  
  8. namespace CryptoUtils {
  9.  
  10.   public class Cryptography {
  11.  
  12.     public enum HashType : short {
  13.       [DescriptionAttribute( "SHA1CryptoServiceProvider" )]
  14.       SHA1 = 0,
  15.       [DescriptionAttribute( "SHA256Managed" )]
  16.       SHA256 = 1,
  17.       [DescriptionAttribute( "SHA384Managed" )]
  18.       SHA384 = 2,
  19.       [DescriptionAttribute( "SHA512Managed" )]
  20.       SHA512 = 3,
  21.       [DescriptionAttribute( "MD5CryptoServiceProvider" )]
  22.       MD5 = 4
  23.     }
  24.  
  25.     public static string CreateSalt( ) {
  26.       RandomNumberGenerator rng = RandomNumberGenerator.Create( );
  27.       byte[ ] number = new byte[ 32 ];
  28.       rng.GetBytes( number );
  29.       return Convert.ToBase64String( number );
  30.     }
  31.  
  32.     public static string CreatePasswordHash( string salt, string password, HashType hashType ) {
  33.       string hashString = string.Empty;
  34.       if ( !string.IsNullOrEmpty( password ) ) {
  35.         HashAlgorithm hashAlg = HashAlgorithm.Create( hashType.ToString( ) );
  36.         byte[ ] pwordData = Encoding.Default.GetBytes( salt + password );
  37.         byte[ ] hash = hashAlg.ComputeHash( pwordData );
  38.         hashString = Convert.ToBase64String( hash );
  39.       }
  40.       return hashString;
  41.     }
  42.  
  43.     public static string CreatePasswordHash( string salt, string password ) {
  44.       return CreatePasswordHash( salt, password, HashType.SHA256 );
  45.     }
  46.  
  47.     public static string EncryptPassword( string password, out string salt ) {
  48.       salt = CreateSalt( );
  49.       return CreatePasswordHash( salt, password );
  50.     }
  51.  
  52.  
  53.   }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment