box_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package box
  2. import (
  3. "crypto/rand"
  4. "reflect"
  5. "testing"
  6. "gogs.baozhida.cn/zoie/OAuth-core/config/secrets"
  7. naclbox "golang.org/x/crypto/nacl/box"
  8. )
  9. func TestBox(t *testing.T) {
  10. alicePublicKey, alicePrivateKey, err := naclbox.GenerateKey(rand.Reader)
  11. if err != nil {
  12. t.Fatal(err)
  13. }
  14. bobPublicKey, bobPrivateKey, err := naclbox.GenerateKey(rand.Reader)
  15. if err != nil {
  16. t.Fatal(err)
  17. }
  18. alice, bob := NewSecrets(secrets.PublicKey(alicePublicKey[:]), secrets.PrivateKey(alicePrivateKey[:])), NewSecrets()
  19. if err := alice.Init(); err != nil {
  20. t.Error(err)
  21. }
  22. if err := bob.Init(secrets.PublicKey(bobPublicKey[:]), secrets.PrivateKey(bobPrivateKey[:])); err != nil {
  23. t.Error(err)
  24. }
  25. if alice.String() != "nacl-box" {
  26. t.Error("String() doesn't return nacl-box")
  27. }
  28. aliceSecret := []byte("Why is a raven like a writing-desk?")
  29. if _, err := alice.Encrypt(aliceSecret); err == nil {
  30. t.Error("alice.Encrypt succeded without a public key")
  31. }
  32. enc, err := alice.Encrypt(aliceSecret, secrets.RecipientPublicKey(bob.Options().PublicKey))
  33. if err != nil {
  34. t.Error("alice.Encrypt failed")
  35. }
  36. if _, err := bob.Decrypt(enc); err == nil {
  37. t.Error("bob.Decrypt succeded without a public key")
  38. }
  39. if dec, err := bob.Decrypt(enc, secrets.SenderPublicKey(alice.Options().PublicKey)); err == nil {
  40. if !reflect.DeepEqual(dec, aliceSecret) {
  41. t.Errorf("Bob's decrypted message didn't match Alice's encrypted message: %v != %v", aliceSecret, dec)
  42. }
  43. } else {
  44. t.Errorf("bob.Decrypt failed (%s)", err)
  45. }
  46. bobSecret := []byte("I haven't the slightest idea")
  47. enc, err = bob.Encrypt(bobSecret, secrets.RecipientPublicKey(alice.Options().PublicKey))
  48. if err != nil {
  49. t.Error(err)
  50. }
  51. dec, err := alice.Decrypt(enc, secrets.SenderPublicKey(bob.Options().PrivateKey))
  52. if err == nil {
  53. t.Error(err)
  54. }
  55. dec, err = alice.Decrypt(enc, secrets.SenderPublicKey(bob.Options().PublicKey))
  56. if err != nil {
  57. t.Error(err)
  58. }
  59. if !reflect.DeepEqual(dec, bobSecret) {
  60. t.Errorf("Alice's decrypted message didn't match Bob's encrypted message %v != %v", bobSecret, dec)
  61. }
  62. }