81 lines
2 KiB
Go
81 lines
2 KiB
Go
package encryption
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"os"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"jonasled.dev/jonasled/hostware-vnc-proxy/log"
|
|
)
|
|
|
|
func DecryptMessage(text string) []byte {
|
|
ivLength := 16
|
|
|
|
// Split encrypted message
|
|
textParts := strings.Split(text, ":")
|
|
iv, _ := hex.DecodeString(textParts[0])
|
|
encryptedText, _ := hex.DecodeString(strings.Join(textParts[1:], ":"))
|
|
|
|
// Create AES cipher block
|
|
block, err := aes.NewCipher([]byte(os.Getenv("JWT_SIGN_KEY")))
|
|
if err != nil {
|
|
log.Log.Error("Failed creating AES Cipher: ", err.Error())
|
|
return []byte{}
|
|
}
|
|
|
|
// Create AES decryption stream
|
|
if len(iv) != ivLength {
|
|
log.Log.Error("Failed decrypting message, invalid IV length")
|
|
return []byte{}
|
|
}
|
|
stream := cipher.NewCBCDecrypter(block, iv)
|
|
|
|
// Decrypt the message
|
|
decrypted := make([]byte, len(encryptedText))
|
|
stream.CryptBlocks(decrypted, encryptedText)
|
|
|
|
re := regexp.MustCompile(`[[:cntrl:]]`)
|
|
cleanedData := re.ReplaceAll(decrypted, nil)
|
|
|
|
// Unpad if necessary
|
|
return cleanedData
|
|
}
|
|
|
|
func EncryptMessage(plainText string) string {
|
|
ivLength := 16
|
|
|
|
// Generate a random IV
|
|
iv := make([]byte, ivLength)
|
|
if _, err := rand.Read(iv); err != nil {
|
|
log.Log.Error("Failed to generate IV: ", err.Error())
|
|
return ""
|
|
}
|
|
|
|
// Create AES cipher block
|
|
block, err := aes.NewCipher([]byte(os.Getenv("JWT_SIGN_KEY")))
|
|
if err != nil {
|
|
log.Log.Error("Failed creating AES Cipher: ", err.Error())
|
|
return ""
|
|
}
|
|
|
|
// Pad the plaintext to be a multiple of the block size
|
|
blockSize := block.BlockSize()
|
|
padding := blockSize - len(plainText)%blockSize
|
|
paddedText := append([]byte(plainText), bytes.Repeat([]byte{byte(padding)}, padding)...)
|
|
|
|
// Create AES encryption stream
|
|
encrypted := make([]byte, len(paddedText))
|
|
stream := cipher.NewCBCEncrypter(block, iv)
|
|
stream.CryptBlocks(encrypted, paddedText)
|
|
|
|
// Combine IV and encrypted text
|
|
encryptedMessage := fmt.Sprintf("%s:%s", hex.EncodeToString(iv), hex.EncodeToString(encrypted))
|
|
|
|
return encryptedMessage
|
|
}
|