From 074bf565c0bbb7757915c0e4fb84e77677c7cfd2 Mon Sep 17 00:00:00 2001 From: Livio Amstutz Date: Tue, 17 Dec 2019 15:21:31 +0100 Subject: [PATCH] copy crypto to utils --- pkg/op/crypto.go | 8 ++++-- pkg/utils/crypto.go | 70 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 3 deletions(-) create mode 100644 pkg/utils/crypto.go diff --git a/pkg/op/crypto.go b/pkg/op/crypto.go index 420c32f..e95157d 100644 --- a/pkg/op/crypto.go +++ b/pkg/op/crypto.go @@ -1,6 +1,8 @@ package op -import "github.com/caos/utils/crypto" +import ( + "github.com/caos/oidc/pkg/utils" +) type Crypto interface { Encrypt(string) (string, error) @@ -16,9 +18,9 @@ func NewAESCrypto(key [32]byte) Crypto { } func (c *aesCrypto) Encrypt(s string) (string, error) { - return crypto.EncryptAES(s, c.key) + return utils.EncryptAES(s, c.key) } func (c *aesCrypto) Decrypt(s string) (string, error) { - return crypto.DecryptAES(s, c.key) + return utils.DecryptAES(s, c.key) } diff --git a/pkg/utils/crypto.go b/pkg/utils/crypto.go new file mode 100644 index 0000000..05acb75 --- /dev/null +++ b/pkg/utils/crypto.go @@ -0,0 +1,70 @@ +package utils + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "encoding/base64" + "errors" + "io" +) + +func EncryptAES(data string, key string) (string, error) { + encrypted, err := EncryptBytesAES([]byte(data), key) + if err != nil { + return "", err + } + + return base64.URLEncoding.EncodeToString(encrypted), nil +} + +func EncryptBytesAES(plainText []byte, key string) ([]byte, error) { + + block, err := aes.NewCipher([]byte(key)) + if err != nil { + return nil, err + } + + cipherText := make([]byte, aes.BlockSize+len(plainText)) + iv := cipherText[:aes.BlockSize] + if _, err = io.ReadFull(rand.Reader, iv); err != nil { + return nil, err + } + + stream := cipher.NewCFBEncrypter(block, iv) + stream.XORKeyStream(cipherText[aes.BlockSize:], plainText) + + return cipherText, nil +} + +func DecryptAES(data string, key string) (string, error) { + text, err := base64.URLEncoding.DecodeString(data) + if err != nil { + return "", nil + } + decrypted, err := DecryptBytesAES(text, key) + if err != nil { + return "", err + } + return string(decrypted), nil +} + +func DecryptBytesAES(cipherText []byte, key string) ([]byte, error) { + + block, err := aes.NewCipher([]byte(key)) + if err != nil { + return nil, err + } + + if len(cipherText) < aes.BlockSize { + err = errors.New("Ciphertext block size is too short!") + return nil, err + } + iv := cipherText[:aes.BlockSize] + cipherText = cipherText[aes.BlockSize:] + + stream := cipher.NewCFBDecrypter(block, iv) + stream.XORKeyStream(cipherText, cipherText) + + return cipherText, err +}