Implement a bit of Encryption
This commit is contained in:
@@ -6,26 +6,33 @@ package util
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
)
|
||||
|
||||
func GenTodayKey() string {
|
||||
key := []byte(time.Now().Format(fmt.Sprintf("%s%s%s ", time.DateOnly, time.DateOnly, time.DateOnly)))
|
||||
return hex.EncodeToString(key) //convert to string for saving
|
||||
}
|
||||
|
||||
func Encrypt(key, input string) (string, error) {
|
||||
key, _ := hex.DecodeString(key)
|
||||
btKey, _ := hex.DecodeString(key)
|
||||
plaintext := []byte(input)
|
||||
|
||||
// Create a new Cipher Block from the key
|
||||
block, err := aes.NewCipher(key)
|
||||
block, err := aes.NewCipher(btKey)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
|
||||
iv := ciphertext[:aes.BlockSize]
|
||||
if _, err := io.ReadFull(rand.reader, iv); err != nil {
|
||||
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -37,16 +44,16 @@ func Encrypt(key, input string) (string, error) {
|
||||
}
|
||||
|
||||
func Decrypt(key, input string) (string, error) {
|
||||
key, _ := hex.DecodeString(key)
|
||||
btKey, _ := hex.DecodeString(key)
|
||||
ciphertext, _ := base64.URLEncoding.DecodeString(input)
|
||||
|
||||
block, err := aes.NewCipher(key)
|
||||
block, err := aes.NewCipher(btKey)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if len(ciphertext) < aes.BlockSize {
|
||||
return errors.New("ciphertext is too short")
|
||||
return "", errors.New("ciphertext is too short")
|
||||
}
|
||||
iv := ciphertext[:aes.BlockSize]
|
||||
ciphertext = ciphertext[aes.BlockSize:]
|
||||
|
||||
Reference in New Issue
Block a user