Example #1
0
// Decrypts a byte slice using secretKey.
func Decrypt(ciphertext []byte, secretKey []byte) ([]byte, error) {
	aes, err := aes.NewCipher(secretKey)
	if err != nil {
		return nil, err
	}

	if (len(ciphertext) % aes.BlockSize()) > 0 {
		return nil, fmt.Errorf("input length %d is not a multiple of blocksize %d", len(ciphertext), aes.BlockSize())
	}

	iv := ciphertext[:aes.BlockSize()]
	cbc := cipher.NewCBCDecrypter(aes, iv)
	ciphertext = ciphertext[len(iv):]
	// decrypt in-place
	cbc.CryptBlocks(ciphertext, ciphertext)
	unpadded, err := pkcsUnpad(ciphertext, aes.BlockSize())
	if err != nil {
		return nil, err
	}
	return unpadded, err
}
Example #2
0
// Encrypts a slice of bytes using secretKey.
func Encrypt(plaintext []byte, secretKey []byte) ([]byte, error) {
	aes, err := aes.NewCipher(secretKey)
	if err != nil {
		return nil, err
	}

	iv := make([]byte, aes.BlockSize())
	_, err = io.ReadFull(rand.Reader, iv)
	if err != nil {
		return nil, err
	}

	cbc := cipher.NewCBCEncrypter(aes, iv)
	padded := pkcsPad(plaintext, aes.BlockSize())
	// put the IV at the beginning of the ciphertext
	encrypted := make([]byte, len(iv)+len(padded))
	copy(encrypted[:len(iv)], iv)
	cbc.CryptBlocks(encrypted[len(iv):], padded)

	return encrypted, nil
}