Skip to content

Commit

Permalink
fix key length check
Browse files Browse the repository at this point in the history
  • Loading branch information
mihir20 committed Sep 6, 2024
1 parent 6408ce2 commit 455b1ad
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
8 changes: 8 additions & 0 deletions encrypt/aes_cfb.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ type encryptionAESCFB struct {
}

func (e *encryptionAESCFB) Encrypt(src []byte, key string) ([]byte, error) {
if len(key) != e.level/8 {
return nil, fmt.Errorf("key length must be %d bytes", e.level/8)
}

block, err := aes.NewCipher([]byte(key))
if err != nil {
return nil, err
Expand All @@ -31,6 +35,10 @@ func (e *encryptionAESCFB) Encrypt(src []byte, key string) ([]byte, error) {
}

func (e *encryptionAESCFB) Decrypt(src []byte, key string) ([]byte, error) {
if len(key) != e.level/8 {
return nil, fmt.Errorf("key length must be %d bytes", e.level/8)
}

block, err := aes.NewCipher([]byte(key))
if err != nil {
return nil, err
Expand Down
8 changes: 8 additions & 0 deletions encrypt/aes_gcm.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ type encryptionAESGCM struct {
}

func (e *encryptionAESGCM) Encrypt(src []byte, key string) ([]byte, error) {
if len(key) != e.level/8 {
return nil, fmt.Errorf("key length must be %d bytes", e.level/8)
}

block, err := aes.NewCipher([]byte(key))
if err != nil {
return nil, err
Expand All @@ -33,6 +37,10 @@ func (e *encryptionAESGCM) Encrypt(src []byte, key string) ([]byte, error) {
}

func (e *encryptionAESGCM) Decrypt(src []byte, key string) ([]byte, error) {
if len(key) != e.level/8 {
return nil, fmt.Errorf("key length must be %d bytes", e.level/8)
}

block, err := aes.NewCipher([]byte(key))
if err != nil {
return nil, err
Expand Down
3 changes: 3 additions & 0 deletions encrypt/encrypt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ func Test_EncryptDecrypt(t *testing.T) {
require.NoError(t, err)

plaintext := loremIpsumDolor
_, err = encrypter.Encrypt(plaintext, key[:len(key)-1])
require.Error(t, err)

ciphertext, err := encrypter.Encrypt(plaintext, key)
require.NoError(t, err)

Expand Down

0 comments on commit 455b1ad

Please sign in to comment.