Skip to content

Commit

Permalink
Merge pull request #13 from ermos/12-fix-return_statements-issue-in-i…
Browse files Browse the repository at this point in the history
…nternalpkggoliathdecryptgo

refact(goliath): create a function for remove padding
  • Loading branch information
ermos authored Mar 11, 2023
2 parents 5938cb8 + 81d6878 commit ba8edc6
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 11 deletions.
9 changes: 1 addition & 8 deletions internal/pkg/goliath/decrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,5 @@ func DecryptData(content string, masterPassword string) (b []byte, err error) {
plainText := make([]byte, len(cipherText))
mode.CryptBlocks(plainText, cipherText)

// Remove padding
padLen := int(plainText[len(plainText)-1])
if padLen > aes.BlockSize || padLen > len(plainText) {
return nil, errors.New("invalid padding")
}

b = plainText[:len(plainText)-padLen]
return
return removePaddingPKCS5(plainText)
}
2 changes: 1 addition & 1 deletion internal/pkg/goliath/encrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func EncryptData(data []byte, masterPassword string) (s string, err error) {
}

blockSize := block.BlockSize()
paddedData := paddingPKCS5(data, blockSize)
paddedData := addPaddingPKCS5(data, blockSize)
cipherText := make([]byte, len(paddedData))
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(cipherText, paddedData)
Expand Down
16 changes: 14 additions & 2 deletions internal/pkg/goliath/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,30 @@ package goliath

import (
"bytes"
"crypto/aes"
"crypto/hmac"
"crypto/sha256"
"errors"
)

// paddingPKCS5 adds PKCS#5 padding to the given data to make its length a multiple of the block size.
// addPaddingPKCS5 adds PKCS#5 padding to the given data to make its length a multiple of the block size.
// https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS#5_and_PKCS#7
func paddingPKCS5(data []byte, blockSize int) []byte {
func addPaddingPKCS5(data []byte, blockSize int) []byte {
padLen := blockSize - len(data)%blockSize
pad := bytes.Repeat([]byte{byte(padLen)}, padLen)
return append(data, pad...)
}

// removePaddingPKCS5 remove PKCS#5 padding.
func removePaddingPKCS5(data []byte) ([]byte, error) {
padLen := int(data[len(data)-1])
if padLen > aes.BlockSize || padLen > len(data) {
return nil, errors.New("invalid padding")
}

return data[:len(data)-padLen], nil
}

// computeHMAC computes the HMAC-SHA256 tag for the given data and key.
func computeHMAC(data []byte, key []byte) []byte {
mac := hmac.New(sha256.New, key)
Expand Down

0 comments on commit ba8edc6

Please sign in to comment.