encrypt.go
encrypt.go - Overview
This file provides utility functions for encryption and decryption using AES in counter mode (CTR). It includes functions for XORing data with a key stream, generating initialization vectors (IVs), and streaming encryption/decryption.
Detailed Documentation
XORBlock
Purpose: Encrypts or decrypts the source data using AES in counter mode (CTR) and XORs the result with the initialization vector (IV). It can be used for both encryption and decryption because XOR is its own inverse.
Parameters:
dst
([]byte): The destination buffer where the result will be written.src
([]byte): The source data to be encrypted or decrypted.key
([]byte): The AES encryption key.iv
([]byte): The initialization vector (IV) for the CTR mode. The IV must be the same size as the AES block size.
Returns:
error
: An error if the AES cipher initialization fails, nil otherwise.
XORBlockAllocate
Purpose: Encrypts or decrypts the source data using AES in counter mode (CTR) and XORs the result with the initialization vector (IV). This function allocates a new buffer for the destination.
Parameters:
src
([]byte): The source data to be encrypted or decrypted.key
([]byte): The AES encryption key.iv
([]byte): The initialization vector (IV) for the CTR mode. The IV must be the same size as the AES block size.
Returns:
[]byte
: The destination buffer containing the encrypted/decrypted data.error
: An error if the AES cipher initialization fails, nil otherwise.
XORBlockStream
Purpose: Encrypts or decrypts the source data using AES in counter mode (CTR) and XORs the result with the initialization vector (IV), writing the output to a stream.
Parameters:
w
(io.Writer): The destination stream to write the encrypted/decrypted data to.src
([]byte): The source data to be encrypted or decrypted.key
([]byte): The AES encryption key.iv
([]byte): The initialization vector (IV) for the CTR mode. The IV must be the same size as the AES block size.
Returns:
error
: An error if the AES cipher initialization fails or if there's an error during the streaming process. The error is wrapped usingWrapf
to add context.
GenerateIV
Purpose: Generates a random initialization vector (IV) suitable for AES encryption.
Parameters:
- None
Returns:
[]byte
: A randomly generated IV with the size of the AES block size.error
: An error if the random number generation fails, nil otherwise.