sodium_test.go 1.3 KB
Newer Older
Jordan Sissel's avatar
.  
Jordan Sissel committed
1 2 3
package sodium

import "fmt"
Jordan Sissel's avatar
- tests  
Jordan Sissel committed
4
import "testing"
5
import "bytes"
Jordan Sissel's avatar
.  
Jordan Sissel committed
6

Jordan Sissel's avatar
- tests  
Jordan Sissel committed
7
func ExampleBox() {
Jordan Sissel's avatar
.  
Jordan Sissel committed
8 9 10
  pk, sk := CryptoBoxKeypair()
  s := NewSession(pk, sk)

Jordan Sissel's avatar
- tests  
Jordan Sissel committed
11
  original := "hello world asldkfj alsdkfj alsdkfj alwketj alwkejt lawkejt lawketjlk j"
Jordan Sissel's avatar
.  
Jordan Sissel committed
12

Jordan Sissel's avatar
- tests  
Jordan Sissel committed
13 14
  // Encrypt the original text
  ciphertext, nonce := s.Box([]byte(original))
Jordan Sissel's avatar
.  
Jordan Sissel committed
15

Jordan Sissel's avatar
- tests  
Jordan Sissel committed
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
  // Decrypt the ciphertext 
  plaintext := string(s.Open(nonce, ciphertext))

  fmt.Printf("%s", plaintext)
  // Output: hello world asldkfj alsdkfj alsdkfj alwketj alwkejt lawkejt lawketjlk j
}

func TestNonceGeneration(t *testing.T) {
  // This is best effort, obviously. The nonce generator is expected to never
  // produce the same nonce twice, and the most naive test we can do is to
  // require that two nonces are not the same.
  pk, sk := CryptoBoxKeypair()
  s := NewSession(pk, sk)

  original := "hello world"
  _, nonce := s.Box([]byte(original))
  _, nonce2 := s.Box([]byte(original))

34
  if bytes.Equal(nonce, nonce2) {
Jordan Sissel's avatar
- tests  
Jordan Sissel committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
    t.Fatal("Two Box() calls generated the same nonce")
  }
}

func BenchmarkBox(b *testing.B) {
  b.StopTimer()
  pk, sk := CryptoBoxKeypair()
  s := NewSession(pk, sk)

  original := "hello world"

  b.StartTimer()
  for i := 0; i < b.N; i++ {
    ciphertext, nonce := s.Box([]byte(original))
    //plaintext := string(s.Open(nonce, ciphertext))
    s.Open(nonce, ciphertext)
  }
Jordan Sissel's avatar
.  
Jordan Sissel committed
52
}