33
44namespace PBKDF2Hasher
55{
6- public class Hasher
6+ private static byte [ ] GenerateSalt ( )
77 {
8+ var csprng = new RNGCryptoServiceProvider ( ) ;
9+ var salt = new byte [ 32 ] ;
10+ csprng . GetBytes ( salt ) ;
11+ return salt ;
12+ }
813
9- public static byte [ ] GenerateSalt ( )
10- {
11- var csprng = new RNGCryptoServiceProvider ( ) ;
12- var salt = new byte [ 32 ] ;
13- csprng . GetBytes ( salt ) ;
14- Console . WriteLine ( "Salt generated - {0}" , Convert . ToBase64String ( salt ) ) ;
15- return salt ;
16- }
17-
18- public static int GetIterations ( )
19- {
20- Console . WriteLine ( "Please enter a number of iterations. If no input is given the program will default to 1 million: " ) ;
21-
22- int iterations ;
23-
24- string input = Console . ReadLine ( ) ;
25- if ( input == "" )
26- {
27- Console . WriteLine ( "Using default iterations" ) ;
28- return 1000000 ;
29- }
30- try
31- {
32- iterations = Int32 . Parse ( input ) ;
33- }
34- catch ( FormatException )
35- {
36- Console . WriteLine ( "Please enter a valid number" ) ;
37- return GetIterations ( ) ;
38- }
39- return iterations ;
40- }
14+ public static ( byte [ ] hash , byte [ ] salt ) pbkdf2hash ( string password )
15+ {
4116
42- public static int Main ( string [ ] args )
17+ string password = "passwd" ;
18+ byte [ ] salt = GenerateSalt ( ) ; //warning shouldnt be random salts - change when you try and decrypt no?
19+ int iterations = 100000 ;
20+ byte [ ] hashValue ;
21+ using ( var pbkdf2 = new Rfc2898DeriveBytes ( password , salt , iterations ) )
4322 {
44- if ( args . Length > 3 || args . Length == 0 )
45- {
46- Console . WriteLine ( "Please give a word to be hashed, and optionally a salt and an iteration number" ) ;
47- return 1 ;
48- }
49-
50- Byte [ ] salt ;
51- int iterations ;
52-
53- if ( args . Length > 1 )
54- {
55- salt = Convert . FromBase64String ( args [ 1 ] ) ;
56- }
57- else
58- {
59- salt = GenerateSalt ( ) ;
60- }
61-
62- if ( args . Length == 3 )
63- {
64- iterations = Convert . ToInt32 ( args [ 3 ] ) ;
65- }
66- else
67- {
68- iterations = GetIterations ( ) ;
69-
70- }
71-
72- byte [ ] hashValue ;
73-
74- //Generate hash using salt
75- using ( var pbkdf2 = new Rfc2898DeriveBytes ( args [ 0 ] , salt , iterations ) )
76- {
77- Console . WriteLine ( "Hashing..." ) ;
78- hashValue = pbkdf2 . GetBytes ( 64 ) ;
79- }
80-
81- Console . WriteLine ( "\n Hash: " + Convert . ToBase64String ( hashValue ) + "\n " + "Salt: " + Convert . ToBase64String ( salt ) ) ;
82-
83-
84- return 0 ;
23+ hashValue = pbkdf2 . GetBytes ( 32 ) ;
8524 }
25+ return ( hashValue , salt ) ;
8626 }
87- }
27+ }
0 commit comments