I tried to use the following tutorial:
https://golangdocs.com/aes-encryption-decryption-in-golang
In order to encrypt/decrypt text using AES256 with Go,
It seems to work with plain strings, but not with JSON encoded structure.
I don't understand why, because I thought JSON encoded data were strings as well.
The part of the code dealing with plain strings is commented with Using trings
.
// Using strings
pt := "This is a secret"
c := EncryptAES([]byte(key), []byte(pt))
fmt.Printf("Initial string: %#v\n", pt)
fmt.Printf("Coded: %v\n", c)
decoded := DecryptAES([]byte(key), c)
fmt.Printf("Decoded: %s\n", decoded)
The part of the code after the comment Using JSON strings
is the part which doesn't seem to word as expected.
// Using JSON strings
p2 := []record{{Name: "John", Age: 20}, {Name: "Jane", Age: 25}}
m2, _ := json.Marshal(p2)
fmt.Printf("m2 = %s\n", string(m2))
fmt.Printf("m2 = %#v\n", string(m2))
coded := EncryptAES([]byte(key), m2)
decoded = DecryptAES([]byte(key), coded)
fmt.Printf("Decoded: %s\n", decoded)
What am I doing wrong?
I'm using Go: go version go1.18 darwin/arm64
package main
import (
"crypto/aes"
"encoding/json"
"fmt"
)
func CheckError(err error) {
if err != nil {
panic(err)
}
}
type record struct {
Name string `json:"first_name"`
Age int `json:"age"`
}
func main() {
// cipher key
key := "thisis32bitlongpassphraseimusing"
fmt.Printf("len of key %d\n", len(key))
// Using strings
pt := "This is a secret"
c := EncryptAES([]byte(key), []byte(pt))
fmt.Printf("Initial string: %#v\n", pt)
fmt.Printf("Coded: %v\n", c)
decoded := DecryptAES([]byte(key), c)
fmt.Printf("Decoded: %s\n", decoded)
// Using JSON strings
p2 := []record{{Name: "John", Age: 20}, {Name: "Jane", Age: 25}}
m2, _ := json.Marshal(p2)
fmt.Printf("m2 = %s\n", string(m2))
fmt.Printf("m2 = %#v\n", string(m2))
coded := EncryptAES([]byte(key), m2)
decoded = DecryptAES([]byte(key), coded)
fmt.Printf("Decoded: %s\n", decoded)
}
func EncryptAES(key []byte, plaintext []byte) []byte {
c, err := aes.NewCipher(key)
CheckError(err)
out := make([]byte, len(plaintext))
c.Encrypt(out, []byte(plaintext))
return out
}
func DecryptAES(key []byte, ct []byte) []byte {
c, err := aes.NewCipher(key)
CheckError(err)
pt := make([]byte, len(ct))
c.Decrypt(pt, ct)
return pt
}