You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.3 KiB

  1. package cryptostore_test
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/assert"
  5. "github.com/stretchr/testify/require"
  6. cmn "github.com/tendermint/tmlibs/common"
  7. "github.com/tendermint/go-crypto/keys/cryptostore"
  8. )
  9. func TestNoopEncoder(t *testing.T) {
  10. assert, require := assert.New(t), require.New(t)
  11. noop := cryptostore.Noop
  12. key := cryptostore.GenEd25519.Generate(cmn.RandBytes(16))
  13. key2 := cryptostore.GenSecp256k1.Generate(cmn.RandBytes(16))
  14. _, b, err := noop.Encrypt(key, "encode")
  15. require.Nil(err)
  16. assert.NotEmpty(b)
  17. _, b2, err := noop.Encrypt(key2, "encode")
  18. require.Nil(err)
  19. assert.NotEmpty(b2)
  20. assert.NotEqual(b, b2)
  21. // note the decode with a different password works - not secure!
  22. pk, err := noop.Decrypt(nil, b, "decode")
  23. require.Nil(err)
  24. require.NotNil(pk)
  25. assert.Equal(key, pk)
  26. pk2, err := noop.Decrypt(nil, b2, "kggugougp")
  27. require.Nil(err)
  28. require.NotNil(pk2)
  29. assert.Equal(key2, pk2)
  30. }
  31. func TestSecretBox(t *testing.T) {
  32. assert, require := assert.New(t), require.New(t)
  33. enc := cryptostore.SecretBox
  34. key := cryptostore.GenEd25519.Generate(cmn.RandBytes(16))
  35. pass := "some-special-secret"
  36. s, b, err := enc.Encrypt(key, pass)
  37. require.Nil(err)
  38. assert.NotEmpty(b)
  39. // decoding with a different pass is an error
  40. pk, err := enc.Decrypt(s, b, "decode")
  41. require.NotNil(err)
  42. require.True(pk.Empty())
  43. // but decoding with the same passphrase gets us our key
  44. pk, err = enc.Decrypt(s, b, pass)
  45. require.Nil(err)
  46. assert.Equal(key, pk)
  47. }
  48. func TestSecretBoxNoPass(t *testing.T) {
  49. assert, require := assert.New(t), require.New(t)
  50. enc := cryptostore.SecretBox
  51. key := cryptostore.GenEd25519.Generate(cmn.RandBytes(16))
  52. cases := []struct {
  53. encode string
  54. decode string
  55. valid bool
  56. }{
  57. {"foo", "foo", true},
  58. {"foo", "food", false},
  59. {"", "", true},
  60. {"", "a", false},
  61. {"a", "", false},
  62. }
  63. for i, tc := range cases {
  64. s, b, err := enc.Encrypt(key, tc.encode)
  65. require.Nil(err, "%d: %+v", i, err)
  66. assert.NotEmpty(b, "%d", i)
  67. pk, err := enc.Decrypt(s, b, tc.decode)
  68. if tc.valid {
  69. require.Nil(err, "%d: %+v", i, err)
  70. assert.Equal(key, pk, "%d", i)
  71. } else {
  72. require.NotNil(err, "%d", i)
  73. }
  74. }
  75. // now let's make sure raw bytes also work...
  76. b := key.Bytes()
  77. pk, err := enc.Decrypt(nil, b, "")
  78. require.Nil(err, "%+v", err)
  79. assert.Equal(key, pk)
  80. }