secretbox_test.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package secretbox
  2. import (
  3. "encoding/base64"
  4. "reflect"
  5. "testing"
  6. "gogs.baozhida.cn/zoie/OAuth-core/config/secrets"
  7. )
  8. func TestSecretBox(t *testing.T) {
  9. secretKey, err := base64.StdEncoding.DecodeString("4jbVgq8FsAV7vy+n8WqEZrl7BUtNqh3fYT5RXzXOPFY=")
  10. if err != nil {
  11. t.Fatal(err)
  12. }
  13. s := NewSecrets()
  14. if err := s.Init(); err == nil {
  15. t.Error("Secretbox accepted an empty secret key")
  16. }
  17. if err := s.Init(secrets.Key([]byte("invalid"))); err == nil {
  18. t.Error("Secretbox accepted a secret key that is invalid")
  19. }
  20. if err := s.Init(secrets.Key(secretKey)); err != nil {
  21. t.Fatal(err)
  22. }
  23. o := s.Options()
  24. if !reflect.DeepEqual(o.Key, secretKey) {
  25. t.Error("Init() didn't set secret key correctly")
  26. }
  27. if s.String() != "nacl-secretbox" {
  28. t.Error(s.String() + " should be nacl-secretbox")
  29. }
  30. // Try 10 times to get different nonces
  31. for i := 0; i < 10; i++ {
  32. message := []byte(`Can you hear me, Major Tom?`)
  33. encrypted, err := s.Encrypt(message)
  34. if err != nil {
  35. t.Errorf("Failed to encrypt message (%s)", err)
  36. }
  37. decrypted, err := s.Decrypt(encrypted)
  38. if err != nil {
  39. t.Errorf("Failed to decrypt encrypted message (%s)", err)
  40. }
  41. if !reflect.DeepEqual(message, decrypted) {
  42. t.Errorf("Decrypted Message dod not match encrypted message")
  43. }
  44. }
  45. }