Skip to content

Instantly share code, notes, and snippets.

@temoto
Created February 27, 2013 22:37
Show Gist options
  • Save temoto/5052503 to your computer and use it in GitHub Desktop.
Save temoto/5052503 to your computer and use it in GitHub Desktop.
Example of AES (Rijndael) CFB encryption in Go. IMHO, http://golang.org/pkg/crypto/cipher/ could benefit a lot from similar snippet.
package main
import (
"crypto/aes"
"crypto/cipher"
"fmt"
)
func EncryptAESCFB(dst, src, key, iv []byte) error {
aesBlockEncrypter, err := aes.NewCipher([]byte(key))
if err != nil {
return err
}
aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, iv)
aesEncrypter.XORKeyStream(dst, src)
return nil
}
func DecryptAESCFB(dst, src, key, iv []byte) error {
aesBlockDecrypter, err := aes.NewCipher([]byte(key))
if err != nil {
return nil
}
aesDecrypter := cipher.NewCFBDecrypter(aesBlockDecrypter, iv)
aesDecrypter.XORKeyStream(dst, src)
return nil
}
func main() {
const key16 = "1234567890123456"
const key24 = "123456789012345678901234"
const key32 = "12345678901234567890123456789012"
var key = key16
var msg = "message"
var iv = []byte(key)[:aes.BlockSize] // Using IV same as key is probably bad
var err error
// Encrypt
encrypted := make([]byte, len(msg))
err = EncryptAESCFB(encrypted, []byte(msg), []byte(key), iv)
if err != nil {
panic(err)
}
fmt.Printf("Encrypting %v %s -> %v\n", []byte(msg), msg, encrypted)
// Decrypt
decrypted := make([]byte, len(msg))
err = DecryptAESCFB(decrypted, encrypted, []byte(key), iv)
if err != nil {
panic(err)
}
fmt.Printf("Decrypting %v -> %v %s\n", encrypted, decrypted, decrypted)
}
@FrancisVarga
Copy link

@FrancisVarga
Copy link

Thx. mate, you saved my night :)

@kkirsche
Copy link

I would recommend not using CFB but instead use AES-GCM for higher security

@Antisunny
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment