Skip to content

Instantly share code, notes, and snippets.

@wwhtrbbtt
Created August 5, 2021 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wwhtrbbtt/b72c26b33865ea15996f685b71428eda to your computer and use it in GitHub Desktop.
Save wwhtrbbtt/b72c26b33865ea15996f685b71428eda to your computer and use it in GitHub Desktop.
Golang web assembly program that utilizes AES encryption.
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
random "math/rand"
"syscall/js"
"github.com/mergermarket/go-pkcs7"
)
func Encrypt(a js.Value, b []js.Value) interface{} {
var i interface{}
i = "Error"
key_ := fmt.Sprintf("%v", b[0])
unencrypted := fmt.Sprintf("%v", b[1])
key := []byte(key_)
plainText := []byte(unencrypted)
plainText, err := pkcs7.Pad(plainText, aes.BlockSize)
if err != nil {
return i
}
if len(plainText)%aes.BlockSize != 0 {
err := fmt.Errorf(`plainText: "%s" has the wrong block size`, plainText)
i = "Error: " + err.Error()
return i
}
block, err := aes.NewCipher(key)
if err != nil {
i = "Error: " + err.Error()
return i
}
cipherText := make([]byte, aes.BlockSize+len(plainText))
iv := cipherText[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
i = "Error: " + err.Error()
return i
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(cipherText[aes.BlockSize:], plainText)
i = fmt.Sprintf("%x", cipherText)
return i
}
func Decrypt(a js.Value, b []js.Value) interface{} {
var i interface{}
i = "Error"
key_ := fmt.Sprintf("%v", b[0])
encrypted := fmt.Sprintf("%v", b[1])
key := []byte(key_)
cipherText, _ := hex.DecodeString(encrypted)
block, err := aes.NewCipher(key)
if err != nil {
i = "Error: " + err.Error()
return i
}
if len(cipherText) < aes.BlockSize {
i = "Error: Ciphertext to short!"
return i
}
iv := cipherText[:aes.BlockSize]
cipherText = cipherText[aes.BlockSize:]
if len(cipherText)%aes.BlockSize != 0 {
i = "Error: cipherText is not a multiple of the block size"
return i
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(cipherText, cipherText)
cipherText, _ = pkcs7.Unpad(cipherText, aes.BlockSize)
i = string(cipherText)
return i
}
func generateKey(_ js.Value, _ []js.Value) interface{} {
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
b := make([]rune, 32)
for i := range b {
b[i] = letterRunes[random.Intn(len(letterRunes))]
}
var i interface{}
i = string(b)
return i
}
func main() {
c := make(chan struct{}, 0)
js.Global().Set("Encrypt", js.FuncOf(Encrypt))
js.Global().Set("Decrypt", js.FuncOf(Decrypt))
js.Global().Set("Generate", js.FuncOf(generateKey))
<-c
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment