github.com/psiphon-labs/psiphon-tunnel-core@v2.0.28+incompatible/psiphon/common/crypto/nacl/secretbox/example_test.go (about) 1 // Copyright 2016 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 5 package secretbox_test 6 7 import ( 8 "crypto/rand" 9 "encoding/hex" 10 "fmt" 11 "io" 12 13 "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/nacl/secretbox" 14 ) 15 16 func Example() { 17 // Load your secret key from a safe place and reuse it across multiple 18 // Seal calls. (Obviously don't use this example key for anything 19 // real.) If you want to convert a passphrase to a key, use a suitable 20 // package like bcrypt or scrypt. 21 secretKeyBytes, err := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574") 22 if err != nil { 23 panic(err) 24 } 25 26 var secretKey [32]byte 27 copy(secretKey[:], secretKeyBytes) 28 29 // You must use a different nonce for each message you encrypt with the 30 // same key. Since the nonce here is 192 bits long, a random value 31 // provides a sufficiently small probability of repeats. 32 var nonce [24]byte 33 if _, err := io.ReadFull(rand.Reader, nonce[:]); err != nil { 34 panic(err) 35 } 36 37 // This encrypts "hello world" and appends the result to the nonce. 38 encrypted := secretbox.Seal(nonce[:], []byte("hello world"), &nonce, &secretKey) 39 40 // When you decrypt, you must use the same nonce and key you used to 41 // encrypt the message. One way to achieve this is to store the nonce 42 // alongside the encrypted message. Above, we stored the nonce in the first 43 // 24 bytes of the encrypted text. 44 var decryptNonce [24]byte 45 copy(decryptNonce[:], encrypted[:24]) 46 decrypted, ok := secretbox.Open(nil, encrypted[24:], &decryptNonce, &secretKey) 47 if !ok { 48 panic("decryption error") 49 } 50 51 fmt.Println(string(decrypted)) 52 // Output: hello world 53 }