1package cryptutil 2 3import ( 4 "crypto/sha256" 5 "crypto/sha512" 6 "encoding/hex" 7 "fmt" 8 "io/ioutil" 9 "os" 10 "testing" 11) 12 13func TestPasswordHashing(t *testing.T) { 14 t.Parallel() 15 bcryptTests := []struct { 16 plaintext []byte 17 hash []byte 18 }{ 19 { 20 plaintext: []byte("password"), 21 hash: []byte("$2a$14$uALAQb/Lwl59oHVbuUa5m.xEFmQBc9ME/IiSgJK/VHtNJJXASCDoS"), 22 }, 23 } 24 25 for _, tt := range bcryptTests { 26 hashed, err := HashPassword(tt.plaintext) 27 if err != nil { 28 t.Error(err) 29 } 30 31 if err = CheckPasswordHash(hashed, tt.plaintext); err != nil { 32 t.Error(err) 33 } 34 } 35} 36 37// Benchmarks SHA256 on 16K of random data. 38func BenchmarkSHA256(b *testing.B) { 39 data, err := ioutil.ReadFile("testdata/random") 40 if err != nil { 41 b.Fatal(err) 42 } 43 b.SetBytes(int64(len(data))) 44 for i := 0; i < b.N; i++ { 45 _ = sha256.Sum256(data) 46 } 47} 48 49// Benchmarks SHA512/256 on 16K of random data. 50func BenchmarkSHA512_256(b *testing.B) { 51 data, err := ioutil.ReadFile("testdata/random") 52 if err != nil { 53 b.Fatal(err) 54 } 55 b.SetBytes(int64(len(data))) 56 for i := 0; i < b.N; i++ { 57 _ = sha512.Sum512_256(data) 58 } 59} 60 61func BenchmarkBcrypt(b *testing.B) { 62 for i := 0; i < b.N; i++ { 63 _, err := HashPassword([]byte("thisisareallybadpassword")) 64 if err != nil { 65 b.Error(err) 66 break 67 } 68 } 69} 70 71func ExampleHash() { 72 tag := "hashing file for lookup key" 73 contents, err := ioutil.ReadFile("testdata/random") 74 if err != nil { 75 fmt.Printf("could not read file: %v\n", err) 76 os.Exit(1) 77 } 78 digest := Hash(tag, contents) 79 fmt.Println(hex.EncodeToString(digest)) 80 // Output: 9f4c795d8ae5c207f19184ccebee6a606c1fdfe509c793614066d613580f03e1 81} 82