Starting work on Encryption
This commit is contained in:
parent
f58088bfb2
commit
c253ca6fdf
60
util/crypt.go
Normal file
60
util/crypt.go
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
/*
|
||||||
|
Copyright © 2024 Brian Buller <brian@bullercodeworks.com>
|
||||||
|
*/
|
||||||
|
package util
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/aes"
|
||||||
|
"crypto/cipher"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Encrypt(key, input string) (string, error) {
|
||||||
|
key, _ := hex.DecodeString(key)
|
||||||
|
plaintext := []byte(input)
|
||||||
|
|
||||||
|
// Create a new Cipher Block from the key
|
||||||
|
block, err := aes.NewCipher(key)
|
||||||
|
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 {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
stream := cipher.NewCFBEncrypter(block, iv)
|
||||||
|
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
|
||||||
|
|
||||||
|
// Convert to base64
|
||||||
|
return base64.URLEncoding.EncodeToString(ciphertext), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Decrypt(key, input string) (string, error) {
|
||||||
|
key, _ := hex.DecodeString(key)
|
||||||
|
ciphertext, _ := base64.URLEncoding.DecodeString(input)
|
||||||
|
|
||||||
|
block, err := aes.NewCipher(key)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(ciphertext) < aes.BlockSize {
|
||||||
|
return errors.New("ciphertext is too short")
|
||||||
|
}
|
||||||
|
iv := ciphertext[:aes.BlockSize]
|
||||||
|
ciphertext = ciphertext[aes.BlockSize:]
|
||||||
|
|
||||||
|
stream := cipher.NewCFBDecrypter(block, iv)
|
||||||
|
|
||||||
|
// XORKeyStream can work in-place if the two arguments are the same.
|
||||||
|
stream.XORKeyStream(ciphertext, ciphertext)
|
||||||
|
|
||||||
|
return fmt.Sprintf("%s", ciphertext), nil
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user