84 lines
1.9 KiB
Go
Raw Normal View History

2020-11-09 10:05:29 -03:00
package aescbc
2019-10-01 12:22:30 -03:00
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"github.com/pkg/errors"
)
2020-11-09 10:05:29 -03:00
const KeySize = 32
2019-10-01 12:22:30 -03:00
2020-11-09 10:05:29 -03:00
func EncryptPkcs7(key []byte, iv []byte, plaintext []byte) ([]byte, error) {
2019-10-01 12:22:30 -03:00
plaintext = pkcs7Padding(plaintext)
2020-11-09 10:05:29 -03:00
return EncryptNoPadding(key, iv, plaintext)
}
2019-10-01 12:22:30 -03:00
2020-11-09 10:05:29 -03:00
func EncryptNoPadding(key []byte, iv []byte, plaintext []byte) ([]byte, error) {
if len(key) != KeySize {
panic("key does not have the right size")
}
2019-10-01 12:22:30 -03:00
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ciphertext := make([]byte, len(plaintext))
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext, plaintext)
return ciphertext, nil
}
2020-11-09 10:05:29 -03:00
func DecryptPkcs7(key []byte, iv []byte, cypertext []byte) ([]byte, error) {
paddedPlaintext, err := DecryptNoPadding(key, iv, cypertext)
if err != nil {
return nil, err
}
return pkcs7UnPadding(paddedPlaintext)
}
2019-10-01 12:22:30 -03:00
2020-11-09 10:05:29 -03:00
func DecryptNoPadding(key []byte, iv []byte, cypertext []byte) ([]byte, error) {
if len(key) != KeySize {
panic("key does not have the right size")
}
2019-10-01 12:22:30 -03:00
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
plaintext := make([]byte, len(cypertext))
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(plaintext, cypertext)
return plaintext, nil
}
func pkcs7Padding(src []byte) []byte {
padding := aes.BlockSize - len(src)%aes.BlockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padtext...)
}
func pkcs7UnPadding(src []byte) ([]byte, error) {
length := len(src)
unpadding := int(src[length-1])
if unpadding > aes.BlockSize || unpadding == 0 {
return nil, errors.New("invalid pkcs7 padding (unpadding > aes.BlockSize || unpadding == 0)")
}
pad := src[len(src)-unpadding:]
for i := 0; i < unpadding; i++ {
if pad[i] != byte(unpadding) {
return nil, errors.New("invalid pkcs7 padding (pad[i] != unpadding)")
}
}
return src[:(length - unpadding)], nil
}