1

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

Lee
  • 8,354
  • 14
  • 55
  • 90

1 Answers1

6

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.

David Grayson
  • 84,103
  • 24
  • 152
  • 189
  • If the plain text value changes to say "sensitive", then an out of bounds error is thrown? http://play.golang.org/p/qEKAk0Z0mL. Why? – Lee Dec 31 '13 at 09:01
  • Also if the plain text is very long, dst remains the same? (I am clueless on how the algorithms actually work...) – Lee Dec 31 '13 at 09:04
  • 1
    You need to encrypt blocks of a fixed size (and pad those that aren't). See my comment on your question, and please be careful with crypto implementations. – elithrar Dec 31 '13 at 10:41
  • Wow, I never realised it was so tricky...I can't be the only one who needs an encryption library with ```func encrypt(plaintext string, secret string) string``` along with decrypt and hash, that handles all of the complexity for me. – Lee Dec 31 '13 at 12:30
  • 1
    @lee : That library seems to use a fixed IV (I only checked AES), that by definition, should be different each time, so use with care. – siritinga Dec 31 '13 at 13:24