The AesEncryptString function will encrypt a
string using a 256-bit AES (Advanced Encryption Standard) algorithm and returns
a copy of the encrypted data as a base64 encoded string to the caller. The password (or
passphrase) provided by the caller is used to generate a SHA-256 hash
value which is used as part of the encryption process. The identical
password is required to decrypt the data using the
AesDecryptString function.
It is recommended that most applications specify a password value.
If the lpszPassword parameter is NULL or specifies a
zero-length string, a default internal hash value is used. This means
that any other application which uses a NULL password value will be
able to decrypt the data. If the Unicode version of this function is
called, the lpszPassword value will be encoded using UTF-8
prior to the hash value being generated.
Due to how the SHA-256 hash is generated, the encrypted data
cannot be decrypted using another third-party library with the same
password value. It can only be decrypted using the
AesDecryptString function.
The amount of encrypted data returned by this function will always
be larger than original unencrypted data. If your application
dynamically allocates a block of memory to store the encrypted string,
provide a maximum output string size that is at least several hundred bytes
larger than the unencrypted data. If the output string is not
large enough, the function will fail and the GetLastError
function will return ERROR_INSUFFICIENT_BUFFER.
The string provided to this function cannot contain embedded
nulls and and should not be used to encrypt binary data.
If you wish to encrypt binary data, use the
AesEncryptBuffer function. It will perform the same
256-bit AES encryption and return the encrypted data into an buffer
provided by the caller.
If you wish to encrypt the contents of a file, use the
AesEncryptFile function.
This function uses the Microsoft CryptoAPI and the RSA AES
cryptographic provider. This provider may not be available in some
languages, countries or regions. The availability of this provider may
also be constrained by cryptography export restrictions imposed by the
United States or other countries. If the required cryptographic
provider is not available, the function will fail.
BOOL bIsEncrypted = FALSE;
LPCTSTR lpszPassword = _T("NFr-E{Ki3_1w0iV+LI@z");
LPCTSTR lpszPlainText = _T("The quick brown fox jumped over the lazy dog.");
TCHAR szEncryptedText[MAX_STRING_LENGTH];
bIsEncrypted = AesEncryptString(lpszPassword,
lpszPlainText,
-1,
szEncryptedText,
MAX_STRING_LENGTH);
if (bIsEncrypted)
{
_tprintf(_T("The encrypted string is \"%s\"\n"), szEncryptedText);
}