I have implemented AES encryption on an angular app which sends encrypted string to a REST api written in golang which then decrypts it to verify if its a valid key or not.
Encryption and decryption is working on angular app and golang separately but rest API returns Panic when we decrypt string sent from angular app
Following is my code on app to encrypt in component file
import * as CryptoJS from 'crypto-js';
var key = "NPZ8fvABP5pKwU3"; // passphrase used to encrypt
let encrypted_text = CryptoJS.AES.encrypt('Hello World', 'NPZ8fvABP5pKwU3');
When I decrypt it with following code it returns "Hello World" on angular app
var bytes = CryptoJS.AES.decrypt(encrypted_text.toString(), 'NPZ8fvABP5pKwU3');
var plaintext = bytes.toString(CryptoJS.enc.Utf8);
console.log(plaintext);
It fails to return same text in rest api with following code in main.go file
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
)
func decrypt(data []byte, passphrase string) []byte {
key := []byte(createHash(passphrase))
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
gcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
nonceSize := gcm.NonceSize()
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
panic(err.Error())
}
return plaintext
}
func main() {
key2 := "NPZ8fvABP5pKwU3"
key3 := []byte("encrypted string from angular app")
plaintext := decrypt(key3, key2)
fmt.Printf(string(plaintext))
}
func createHash(key string) string {
hasher := md5.New()
hasher.Write([]byte(key))
return hex.EncodeToString(hasher.Sum(nil))
}
https://play.golang.org/p/iGYyg0RB-Zi
returned error
panic: cipher: message authentication failed