Donnerstag, 10. Dezember 2009

Golang: crypto/aes

Here we test the golang aes encryption decryption. We simple encrypt and decrypt a text message with AES-128. That is a key with 16 byte length.

"NewCipher creates and returns a new Cipher. The key argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256."


package main

import (
"crypto/aes";
. "fmt";
"os";
"strings";
)

func main() {
// a 32 byte long message
msg := "This is long message text. len32";
// some key, 16 Byte long
key := []byte{0x2c, 0x88, 0x25, 0x1a, 0xaa, 0xae, 0xc2, 0xa2, 0xaf, 0xe7, 0x84, 0x8a, 0x10, 0xcf, 0xe3, 0x2a};

Println("len of message: ", len(msg));
Println("len of key: ", len(key));
// create the new cipher
c, err := aes.NewCipher(key);
if err != nil {
Println("Error: NewCipher(%d bytes) = %s", len(key), err);
os.Exit(-1);
}

// now we convert our string into 32 long byte array
msgbuf := strings.Bytes(msg);
out := make([]byte, len(msg));

c.Encrypt(msgbuf[0:16], out[0:16]); // encrypt the first half
c.Encrypt(msgbuf[16:32], out[16:32]); // encrypt the second half

Println("len of encrypted: ", len(out));
Println(">> ", out);

// now we decrypt our encrypted text
plain := make([]byte, len(out));
c.Decrypt(out[0:16], plain[0:16]); // decrypt the first half
c.Decrypt(out[16:32], plain[16:32]); // decrypt the second half

Println("msg: ", string(plain));
}

output:

len of message: 32
len of key: 16
len of encrypted: 32
>> [0 173 125 174 152 165 226 181 32 25 196 177 81 243 134 79 55 152 215 72 239 85 123 219 82 30 231 89 185 194 67 203]
msg: This is long message text. len32

2 Kommentare:

  1. http://play.golang.org/p/PoXSLXlK5o here I have some fix for 1.0.3

    AntwortenLöschen
  2. This might have changed recently in the golang API, but in both Encrypt and Decrypt, the first argument is the *destination*. I looks like you are giving it the src as the first arg, however:

    c.Encrypt(msgbuf[0:16], out[0:16])

    Have a look here
    http://golang.org/pkg/crypto/cipher/#Block

    _R

    AntwortenLöschen