Skip to content

Instantly share code, notes, and snippets.

@kiko
Forked from manveru/crypto_block.go
Created April 13, 2010 00:44
Show Gist options
  • Save kiko/364179 to your computer and use it in GitHub Desktop.
Save kiko/364179 to your computer and use it in GitHub Desktop.
package main
import(
. "bytes"
"crypto/aes"
"crypto/rand"
. "crypto/block"
"os"
"io"
"io/ioutil"
. "fmt"
)
func main(){
msg := "This is it foo bar foobar"
// some key, 16 bytes long
key := randBytes(16)
// create the new cipher
cipher, err := aes.NewCipher(key)
if err != nil {
Println("Error: NewCipher(%d bytes) =%s", len(key), err)
os.Exit(1)
}
// the initialization vector...
iv := randBytes(8)
encrypted := Encrypt(cipher, iv, msg)
Println("encrypted:", encrypted)
decrypted := Decrypt(cipher, iv, encrypted)
Println("decrypted:", decrypted)
}
func Encrypt(cipher Cipher, iv []uint8, msg string) (encrypted *Buffer){
encrypted = NewBuffer(make([]byte, 0))
encrypter := NewCTRWriter(cipher, iv, encrypted)
length, error := io.WriteString(encrypter, msg)
if error != nil {
Println("length:", length)
Println("error:", error)
os.Exit(0)
}
return
}
func Decrypt(cipher Cipher, iv []uint8, encrypted *Buffer) (msg string){
decrypter := NewCTRReader(cipher, iv, encrypted)
bytes, error := ioutil.ReadAll(decrypter)
if error == nil {
msg = NewBuffer(bytes).String()
} else {
Println("Error: ioutil.Readall() =>", error)
os.Exit(1)
}
return
}
func randBytes(count int) (bytes []byte){
bytes = make([]byte, 16)
_, err := rand.Read(bytes)
if err != nil {
Println("Error: rand.Rand(%d bytes) =%s", 16, err)
os.Exit(1)
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment