copy crypto to utils

This commit is contained in:
Livio Amstutz 2019-12-17 15:21:31 +01:00
parent 35aa88b939
commit 074bf565c0
2 changed files with 75 additions and 3 deletions

View file

@ -1,6 +1,8 @@
package op package op
import "github.com/caos/utils/crypto" import (
"github.com/caos/oidc/pkg/utils"
)
type Crypto interface { type Crypto interface {
Encrypt(string) (string, error) Encrypt(string) (string, error)
@ -16,9 +18,9 @@ func NewAESCrypto(key [32]byte) Crypto {
} }
func (c *aesCrypto) Encrypt(s string) (string, error) { 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) { func (c *aesCrypto) Decrypt(s string) (string, error) {
return crypto.DecryptAES(s, c.key) return utils.DecryptAES(s, c.key)
} }

70
pkg/utils/crypto.go Normal file
View file

@ -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
}