github.com/n00py/Slackor@v0.0.0-20200610224921-d007fcea1740/internal/crypto/encrypt.go (about) 1 package crypto 2 3 import ( 4 "bytes" 5 "crypto/aes" 6 "crypto/cipher" 7 "encoding/base64" 8 9 "github.com/n00py/Slackor/internal/config" 10 ) 11 12 func PKCS5Padding(ciphertext []byte, blockSize int) []byte { //Used for Crypto 13 padding := blockSize - len(ciphertext)%blockSize 14 padtext := bytes.Repeat([]byte{byte(padding)}, padding) 15 return append(ciphertext, padtext...) 16 } 17 18 func Encrypt(origData []byte) (string, error) { // Encrypt a string 19 block, err := aes.NewCipher(config.CipherKeyBytes) 20 if err != nil { 21 return "", err 22 } 23 blockSize := block.BlockSize() 24 origData = PKCS5Padding(origData, blockSize) 25 blockMode := cipher.NewCBCEncrypter(block, config.CipherIV) 26 crypted := make([]byte, len(origData)) 27 blockMode.CryptBlocks(crypted, origData) 28 return base64.StdEncoding.EncodeToString(crypted), nil 29 } 30 31 func EncryptFile(origData []byte) ([]byte, error) { // Encrypt a file 32 block, err := aes.NewCipher(config.CipherKeyBytes) 33 if err != nil { 34 return nil, err 35 } 36 blockSize := block.BlockSize() 37 origData = PKCS5Padding(origData, blockSize) 38 blockMode := cipher.NewCBCEncrypter(block, config.CipherIV) 39 crypted := make([]byte, len(origData)) 40 blockMode.CryptBlocks(crypted, origData) 41 return crypted, nil 42 }