mirror of
https://github.com/cloudflare/redoctober.git
synced 2026-09-19 06:14:12 +00:00
Move {En,De}cryptCBC and MakeRandom to symcrypt.
The symcrypt package now contains common secret-key code that is redefined in a number of packages.
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
// Package symcrypt contains common symmetric encryption functions.
|
||||
package symcrypt
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"io"
|
||||
)
|
||||
|
||||
// DecryptCBC decrypt bytes using a key and IV with AES in CBC mode.
|
||||
func DecryptCBC(data, iv, key []byte) (decryptedData []byte, err error) {
|
||||
aesCrypt, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ivBytes := append([]byte{}, iv...)
|
||||
|
||||
decryptedData = make([]byte, len(data))
|
||||
aesCBC := cipher.NewCBCDecrypter(aesCrypt, ivBytes)
|
||||
aesCBC.CryptBlocks(decryptedData, data)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// EncryptCBC encrypt data using a key and IV with AES in CBC mode.
|
||||
func EncryptCBC(data, iv, key []byte) (encryptedData []byte, err error) {
|
||||
aesCrypt, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ivBytes := append([]byte{}, iv...)
|
||||
|
||||
encryptedData = make([]byte, len(data))
|
||||
aesCBC := cipher.NewCBCEncrypter(aesCrypt, ivBytes)
|
||||
aesCBC.CryptBlocks(encryptedData, data)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// MakeRandom is a helper that makes a new buffer full of random data.
|
||||
func MakeRandom(length int) ([]byte, error) {
|
||||
bytes := make([]byte, length)
|
||||
_, err := io.ReadFull(rand.Reader, bytes)
|
||||
return bytes, err
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package symcrypt
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"github.com/cloudflare/redoctober/padding"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCrypt(t *testing.T) {
|
||||
msg := []byte("One ping only, please.")
|
||||
padMsg := padding.AddPadding(msg)
|
||||
|
||||
key, err := MakeRandom(16)
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
|
||||
iv, err := MakeRandom(16)
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
|
||||
out, err := EncryptCBC(padMsg, iv, key)
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
|
||||
out, err = DecryptCBC(out, iv, key)
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
|
||||
unpadOut, err := padding.RemovePadding(out)
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
} else if !bytes.Equal(unpadOut, msg) {
|
||||
t.Fatal("Decrypted message doesn't match original plaintext.")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user