简体   繁体   中英

How can I use AES encryption on top of JSON marshalling using Go?

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
}

Here is a working implementation of the encryptFile and decryptFile functions:

(Based on: https://medium.com/@mertkimyonsen/encrypt-a-file-using-go-f1fe3bc7c635 )

func encryptFile(key []byte, plainText []byte) []byte {

    // Creating block of algorithm
    block, err := aes.NewCipher(key)
    if err != nil {
        log.Fatalf("cipher err: %v", err.Error())
    }

    // Creating GCM mode
    gcm, err := cipher.NewGCM(block)
    if err != nil {
        log.Fatalf("cipher GCM err: %v", err.Error())
    }

    // Generating random nonce
    nonce := make([]byte, gcm.NonceSize())
    if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
        log.Fatalf("nonce  err: %v", err.Error())
    }

    // Decrypt file
    cipherText := gcm.Seal(nonce, nonce, plainText, nil)
    return cipherText

}

func decryptFile(key []byte, cipherText []byte) []byte {

    // Creating block of algorithm
    block, err := aes.NewCipher(key)
    if err != nil {
        log.Fatalf("cipher err: %v", err.Error())
    }

    // Creating GCM mode
    gcm, err := cipher.NewGCM(block)
    if err != nil {
        log.Fatalf("cipher GCM err: %v", err.Error())
    }

    // Deattached nonce and decrypt
    nonce := cipherText[:gcm.NonceSize()]
    cipherText = cipherText[gcm.NonceSize():]
    plainText, err := gcm.Open(nil, nonce, cipherText, nil)

    if err != nil {
        log.Fatalf("decrypt file err: %v", err.Error())
    }

    return plainText

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM