LEFT | RIGHT |
(no file at all) | |
| 1 // Copyright 2013 The Go Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style |
| 3 // license that can be found in the LICENSE file. |
| 4 package hkdf_test |
| 5 |
| 6 import ( |
| 7 "bytes" |
| 8 "code.google.com/p/go.crypto/hkdf" |
| 9 "crypto/rand" |
| 10 "crypto/sha1" |
| 11 "fmt" |
| 12 "io" |
| 13 ) |
| 14 |
| 15 // Usage example that expands one master key into three other cryptographically |
| 16 // secure keys. |
| 17 func Example_usage() { |
| 18 // Underlying hash function to use |
| 19 hash := sha1.New |
| 20 |
| 21 // Cryptographically secure - secret - master key |
| 22 master := []byte{0x00, 0x01, 0x02, 0x03} // i.e. NOT this |
| 23 |
| 24 // Non secret salt, optional (can be nil) |
| 25 // Recommended: hash-length sized random |
| 26 salt := make([]byte, hash().Size()) |
| 27 n, err := io.ReadFull(rand.Reader, salt) |
| 28 if n != len(salt) || err != nil { |
| 29 fmt.Println("error:", err) |
| 30 return |
| 31 } |
| 32 |
| 33 // Non secret context specific info, optional (can be nil) |
| 34 // Note, independent from the master key |
| 35 info := []byte{0x03, 0x14, 0x15, 0x92, 0x65} // I like pie |
| 36 |
| 37 // Create the key derivation function |
| 38 hkdf := hkdf.New(hash, master, salt, info) |
| 39 |
| 40 // Generate the required keys |
| 41 keys := make([][]byte, 3) |
| 42 for i := 0; i < len(keys); i++ { |
| 43 keys[i] = make([]byte, 24) |
| 44 n, err := io.ReadFull(hkdf, keys[i]) |
| 45 if n != len(keys[i]) || err != nil { |
| 46 fmt.Println("error:", err) |
| 47 return |
| 48 } |
| 49 } |
| 50 |
| 51 // Keys should contain 192 bit random keys |
| 52 for i := 1; i <= len(keys); i++ { |
| 53 fmt.Printf("Key #%d: %v\n", i, !bytes.Equal(keys[i-1], make([]by
te, 24))) |
| 54 } |
| 55 |
| 56 // Output: |
| 57 // Key #1: true |
| 58 // Key #2: true |
| 59 // Key #3: true |
| 60 } |
LEFT | RIGHT |