Created
April 12, 2010 08:19
-
-
Save manveru/363381 to your computer and use it in GitHub Desktop.
Simple example of stream encryption using AES and CTR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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