mirror of
https://github.com/thomiceli/opengist.git
synced 2024-12-23 13:02:39 +00:00
47 lines
919 B
Go
47 lines
919 B
Go
|
package utils
|
||
|
|
||
|
import (
|
||
|
"crypto/aes"
|
||
|
"crypto/cipher"
|
||
|
"crypto/rand"
|
||
|
"fmt"
|
||
|
"io"
|
||
|
)
|
||
|
|
||
|
func AESEncrypt(key, text []byte) ([]byte, error) {
|
||
|
block, err := aes.NewCipher(key)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
ciphertext := make([]byte, aes.BlockSize+len(text))
|
||
|
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:], text)
|
||
|
|
||
|
return ciphertext, nil
|
||
|
}
|
||
|
|
||
|
func AESDecrypt(key, ciphertext []byte) ([]byte, error) {
|
||
|
block, err := aes.NewCipher(key)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
if len(ciphertext) < aes.BlockSize {
|
||
|
return nil, fmt.Errorf("ciphertext too short")
|
||
|
}
|
||
|
|
||
|
iv := ciphertext[:aes.BlockSize]
|
||
|
ciphertext = ciphertext[aes.BlockSize:]
|
||
|
|
||
|
stream := cipher.NewCFBDecrypter(block, iv)
|
||
|
stream.XORKeyStream(ciphertext, ciphertext)
|
||
|
|
||
|
return ciphertext, nil
|
||
|
}
|