Created
February 27, 2013 22:37
-
-
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.
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 ( | |
"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) | |
} |
Thx. mate, you saved my night :)
I would recommend not using CFB but instead use AES-GCM for higher security
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://play.golang.org/p/lQB_MJENKY