Skip to content

Commit

Permalink
fix: updates encrypt and decrypt functions and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
matt-primrose committed Oct 8, 2024
1 parent 13faffd commit 1c028db
Show file tree
Hide file tree
Showing 6 changed files with 60 additions and 52 deletions.
28 changes: 14 additions & 14 deletions pkg/security/decrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,52 +12,52 @@ import (
"github.com/open-amt-cloud-toolkit/go-wsman-messages/v2/pkg/config"
)

// Decrypt ciphertext using AES-GCM with the provided key.
func (c Crypto) Decrypt(cipherText string, key []byte) ([]byte, error) {
// Decrypt cipher text using AES-GCM with the provided key.
func (c Crypto) Decrypt(cipherText string) (string, error) {
data, err := base64.StdEncoding.DecodeString(cipherText)
if err != nil {
return nil, err
return "", err
}

block, err := aes.NewCipher(key)
block, err := aes.NewCipher([]byte(c.EncryptionKey))
if err != nil {
return nil, err
return "", err
}

gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
return "", err
}

if len(data) < gcm.NonceSize() {
return nil, errors.New("cipher text too short")
return "", errors.New("cipher text too short")
}

nonce, ciphertext := data[:gcm.NonceSize()], data[gcm.NonceSize():]
nonce, cText := data[:gcm.NonceSize()], data[gcm.NonceSize():]

plainText, err := gcm.Open(nil, nonce, ciphertext, nil)
plainText, err := gcm.Open(nil, nonce, cText, nil)
if err != nil {
return nil, err
return "", err
}

return plainText, nil
return string(plainText), nil
}

// Read encrypted data from file and decrypt it.
func (c Crypto) ReadAndDecryptFile(filePath string, key []byte) (config.Configuration, error) {
func (c Crypto) ReadAndDecryptFile(filePath string) (config.Configuration, error) {
encryptedData, err := os.ReadFile(filePath)
if err != nil {
return config.Configuration{}, err
}

decryptedData, err := c.Decrypt(string(encryptedData), key)
decryptedData, err := c.Decrypt(string(encryptedData))
if err != nil {
return config.Configuration{}, err
}

var configuration config.Configuration

err = yaml.Unmarshal(decryptedData, &configuration)
err = yaml.Unmarshal([]byte(decryptedData), &configuration)
if err != nil {
return config.Configuration{}, err
}
Expand Down
46 changes: 25 additions & 21 deletions pkg/security/decrypt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ import (
)

var (
validKey = "ThisismyveryStrongkey32byteslong"
wrongKey = "ThisismyveryStrongkey32bytelong!"
validKey = "Jf3Q2nXJ+GZzN1dbVQms0wbB4+i/5PjL"
wrongKey = "Jf3Q2nXJ+GZzN1dbVQms0wbB4+iwrong"
shortKey = "shortKey"
missingKey = ""
validMessageText = "Hello, World!"
Expand Down Expand Up @@ -111,31 +111,31 @@ func TestDecrypt(t *testing.T) {
key string
expectedError expectedError
errorMsg error
expected []byte
expected string
}{
{
name: "successful decryption",
message: validMessageText,
key: validKey,
expectedError: expectedError{},
errorMsg: nil,
expected: []byte("Hello World"),
expected: "Hello World",
},
{
name: "fail to decode base64",
message: invalidMessageText,
key: validKey,
expectedError: expectedError{Base64Error: true},
errorMsg: base64.CorruptInputError(7),
expected: nil,
expected: "",
},
{
name: "fail to create new cipher",
message: validMessageText,
key: missingKey,
expectedError: expectedError{NewCipherError: true},
errorMsg: aes.KeySizeError(0),
expected: nil,
expected: "",
},
}

Expand All @@ -146,26 +146,28 @@ func TestDecrypt(t *testing.T) {

var err error

var decryptedString []byte
var decryptedString string

cryptor := Crypto{}
cryptor := Crypto{
EncryptionKey: tc.key,
}

if tc.expectedError.Base64Error {
_, err = cryptor.Decrypt(tc.message, []byte(tc.key))
_, err = cryptor.Decrypt(tc.message)
assert.Equal(t, tc.errorMsg, err)
assert.Equal(t, tc.expected, decryptedString)
}

if tc.expectedError.NewCipherError {
encryptedString, _ := cryptor.Encrypt([]byte(tc.message), tc.key)
decryptedString, err = cryptor.Decrypt(encryptedString, []byte(tc.key))
encryptedString, _ := cryptor.Encrypt(tc.message)
decryptedString, err = cryptor.Decrypt(encryptedString)
assert.Equal(t, tc.errorMsg, err)
assert.Equal(t, tc.expected, decryptedString)
}

if !tc.expectedError.Base64Error && !tc.expectedError.NewCipherError {
encryptedString, _ := cryptor.Encrypt([]byte(tc.message), tc.key)
decryptedString, err = cryptor.Decrypt(encryptedString, []byte(tc.key))
encryptedString, err := cryptor.Encrypt(tc.message)

Check failure on line 169 in pkg/security/decrypt_test.go

View workflow job for this annotation

GitHub Actions / runner / golangci-lint

[golangci] reported by reviewdog 🐶 ineffectual assignment to err (ineffassign) Raw Output: pkg/security/decrypt_test.go:169:22: ineffectual assignment to err (ineffassign) encryptedString, err := cryptor.Encrypt(tc.message) ^
decryptedString, err = cryptor.Decrypt(encryptedString)
assert.Equal(t, tc.message, string(decryptedString))
assert.NoError(t, err)
}
Expand All @@ -183,39 +185,39 @@ func TestReadAndDecryptFile(t *testing.T) {
key string
expectedError expectedError
errorMsg error
expected []byte
expected string
}{
{
name: "successful decryption",
filePath: "testing/encryptedConfig.yaml",
key: validKey,
expectedError: expectedError{},
errorMsg: nil,
expected: byteArrayConfigFile,
expected: string(byteArrayConfigFile),
},
{
name: "incorrect key size",
filePath: "testing/encryptedConfig.yaml",
key: shortKey,
expectedError: expectedError{InvalidKeySizeError: true},
errorMsg: aes.KeySizeError(8),
expected: []byte("Hello World"),
expected: "",
},
{
name: "incorrect key",
filePath: "testing/encryptedConfig.yaml",
key: wrongKey,
expectedError: expectedError{AuthenticationError: true},
errorMsg: errors.New("cipher: message authentication failed"),
expected: []byte("Hello World"),
expected: "",
},
{
name: "unable to read file",
filePath: "testing/doesnotexist.yaml",
key: validKey,
expectedError: expectedError{FileReadError: true},
errorMsg: &fs.PathError{Op: "open", Path: "testing/doesnotexist.yaml", Err: syscall.ENOENT},
expected: []byte(""),
expected: "",
},
}

Expand All @@ -224,11 +226,13 @@ func TestReadAndDecryptFile(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
t.Parallel()

cryptor := Crypto{}
_, err := cryptor.ReadAndDecryptFile(test.filePath, []byte(test.key))
cryptor := Crypto{
EncryptionKey: test.key,
}
_, err := cryptor.ReadAndDecryptFile(test.filePath)

if !test.expectedError.InvalidKeySizeError && !test.expectedError.AuthenticationError && !test.expectedError.NewCipherError && !test.expectedError.Base64Error && !test.expectedError.FileReadError {
decryptedFile, err := cryptor.ReadAndDecryptFile(test.filePath, []byte(test.key))
decryptedFile, err := cryptor.ReadAndDecryptFile(test.filePath)
assert.Equal(t, expectedConfigFile, decryptedFile)
assert.NoError(t, err)
} else {
Expand Down
8 changes: 4 additions & 4 deletions pkg/security/encrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import (
)

// Encrypt encrypts a string.
func (c Crypto) Encrypt(plainText []byte, key string) (string, error) {
block, err := aes.NewCipher([]byte(key))
func (c Crypto) Encrypt(plainText string) (string, error) {
block, err := aes.NewCipher([]byte(c.EncryptionKey))
if err != nil {
return "", err
}
Expand All @@ -26,9 +26,9 @@ func (c Crypto) Encrypt(plainText []byte, key string) (string, error) {
return "", err
}

ciphertext := gcm.Seal(nonce, nonce, plainText, nil)
cipherText := gcm.Seal(nonce, nonce, []byte(plainText), nil)

return base64.StdEncoding.EncodeToString(ciphertext), nil
return base64.StdEncoding.EncodeToString(cipherText), nil
}

func (c Crypto) GenerateKey() string {
Expand Down
18 changes: 10 additions & 8 deletions pkg/security/encrypt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,23 @@ func TestEncrypt(t *testing.T) {

tests := []struct {
name string
message []byte
message string
key string
expectedError expectedError
errorMsg error
expected interface{}
}{
{
name: "successful encryption",
message: []byte("test message"),
message: "test message",
key: validKey,
expectedError: expectedError{},
errorMsg: nil,
expected: []byte("test message"),
expected: "test message",
},
{
name: "key too short",
message: []byte("test message"),
message: "test message",
key: shortKey,
expectedError: expectedError{InvalidKeySizeError: true},
errorMsg: aes.KeySizeError(8),
Expand All @@ -45,19 +45,21 @@ func TestEncrypt(t *testing.T) {

var encryptedString string

cryptor := Crypto{}
cryptor := Crypto{
EncryptionKey: tc.key,
}

if !tc.expectedError.Base64Error && !tc.expectedError.NewCipherError && !tc.expectedError.AuthenticationError && !tc.expectedError.FileReadError && !tc.expectedError.InvalidKeySizeError {
encryptedString, err = cryptor.Encrypt(tc.message, tc.key)
encryptedString, err = cryptor.Encrypt(string(tc.message))

Check failure on line 53 in pkg/security/encrypt_test.go

View workflow job for this annotation

GitHub Actions / runner / golangci-lint

[golangci] reported by reviewdog 🐶 unnecessary conversion (unconvert) Raw Output: pkg/security/encrypt_test.go:53:50: unnecessary conversion (unconvert) encryptedString, err = cryptor.Encrypt(string(tc.message)) ^
assert.NoError(t, err)
assert.NotEmpty(t, encryptedString)
decryptedMessage, err := cryptor.Decrypt(encryptedString, []byte(tc.key))
decryptedMessage, err := cryptor.Decrypt(encryptedString)
assert.NoError(t, err)
assert.Equal(t, tc.expected, decryptedMessage)
}

if tc.expectedError.InvalidKeySizeError {
_, err = cryptor.Encrypt(tc.message, tc.key)
_, err = cryptor.Encrypt(string(tc.message))

Check failure on line 62 in pkg/security/encrypt_test.go

View workflow job for this annotation

GitHub Actions / runner / golangci-lint

[golangci] reported by reviewdog 🐶 unnecessary conversion (unconvert) Raw Output: pkg/security/encrypt_test.go:62:36: unnecessary conversion (unconvert) _, err = cryptor.Encrypt(string(tc.message)) ^
assert.Equal(t, tc.errorMsg, err)
assert.Equal(t, tc.expected, encryptedString)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/security/testing/encryptedConfig.yaml
Original file line number Diff line number Diff line change
@@ -1 +1 @@
Ka2VC9bYYZwT99o+N+nnKJtC07FbTztJNeO0ARPWi4cjirxwclvOqu2nXqe4S9tQ4GD1nOPUlx4b+4JoUGjDxG44X1PSnGaANwbWYE1DDdOasF8EspbZh5KQcwdlY8Z17LDy/MPJW63+9AOlEeBhZBprRJFqqQVevdC7UDwQ0Xt5UdaJhypbVpnvQK9AEpsK2TD2Iwor8imnWdC3kvDYHF1620YWg8kZmpmq0v3vA+B+sv88LcHh9pdGvnYl2HDA/zmYrZNGZTkfwlSednDUwQhwvlKSSFscr0h2QjzIVHxDOZ5E4d3kceeWWEPbt10nW1NdxTNFvCGOZ+B8cHKrdrnmU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 additions & 4 deletions pkg/security/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ import (
)

type Cryptor interface {
Decrypt(cipherText string, key []byte) ([]byte, error)
Encrypt(plainText []byte, key string) (string, error)
Decrypt(cipherText string) (string, error)
Encrypt(plainText string) (string, error)
GenerateKey() string
ReadAndDecryptFile(filePath string, key []byte) (config.Configuration, error)
ReadAndDecryptFile(filePath string) (config.Configuration, error)
}

type Crypto struct{}
type Crypto struct {
EncryptionKey string
}

type Storager interface {
GetKeyValue(key string) (string, error)
Expand Down

0 comments on commit 1c028db

Please sign in to comment.