Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions crypter.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,19 @@ func Init(c Crypterer) {
// Encrypt reads plaintext from an io.Reader
// and writes ciphertext to an io.Writer.
func Encrypt(w io.Writer, r io.Reader) error {
if crypter == nil {
return ErrCrypterNotInitialized
}

return crypter.Encrypt(w, r)
}

// Decrypt reads ciphertext from an io.Reader
// and writes plaintext to an io.Writer.
func Decrypt(w io.Writer, r io.Reader) error {
if crypter == nil {
return ErrCrypterNotInitialized
}

return crypter.Decrypt(w, r)
}
32 changes: 32 additions & 0 deletions crypter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,22 @@ func Test_Encrypt(t *testing.T) {
assert.Equal(t, ciphertext, writer.String())
}

func Test_Encrypt_NotInitialized(t *testing.T) {
prev := crypter
t.Cleanup(func() {
crypter = prev
})

crypter = nil

reader := bytes.NewBufferString("Hello World")
writer := new(bytes.Buffer)

err := Encrypt(writer, reader)
require.Error(t, err)
assert.ErrorIs(t, err, ErrCrypterNotInitialized)
}

func Test_Decrypt(t *testing.T) {
crypter = &base64Crypter{}

Expand All @@ -91,3 +107,19 @@ func Test_Decrypt(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, plaintext, writer.String())
}

func Test_Decrypt_NotInitialized(t *testing.T) {
prev := crypter
t.Cleanup(func() {
crypter = prev
})

crypter = nil

reader := bytes.NewBufferString("SGVsbG8gV29ybGQ=")
writer := new(bytes.Buffer)

err := Decrypt(writer, reader)
require.Error(t, err)
assert.ErrorIs(t, err, ErrCrypterNotInitialized)
}
7 changes: 7 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package sqlcrypter

import "errors"

// ErrCrypterNotInitialized indicates that Init() has not been called
// with a valid Crypterer before Encrypt()/Decrypt() usage.
var ErrCrypterNotInitialized = errors.New("sqlcrypter: crypter is not initialized")
Loading