Lee
Lee

Reputation: 8734

Golang AES encryption

I am new to Go and I am trying out the crypto package.

My code looks like:

package main

import "fmt"
import . "crypto/aes"

func main() {
    block, _ := NewCipher([]byte("randomkey"))

    var dst = []byte{}
    var src = []byte("senstive")

    block.Encrypt(dst, src)
    fmt.Println(string(src))
}

I get the following error:

panic: runtime error: invalid memory address or nil pointer dereference.

What am I doing wrong?

My code can be found at the Go playground here

Upvotes: 1

Views: 7344

Answers (1)

David Grayson
David Grayson

Reputation: 87376

I fixed it:

package main

import "fmt"
import "crypto/aes"

func main() {
    bc, err := aes.NewCipher([]byte("key3456789012345"))
    if (err != nil) {
        fmt.Println(err);
    }
    fmt.Printf("The block size is %d\n", bc.BlockSize())

    var dst = make([]byte, 16)
    var src = []byte("sensitive1234567")

    bc.Encrypt(dst, src)
    fmt.Println(dst)
}

In general, you should be checking error codes and carefully reading documentation of every function you call. Also, this is a block cypher so it requires blocks of bytes that are a specific size.

Upvotes: 6

Related Questions