crypto-api-cypher-example/cypher.c

102 lines
3.0 KiB
C

#include <windows.h>
#include <wincrypt.h>
#include <stdio.h>
void HandleError(const char* message) {
printf("%s\n", message);
exit(1);
}
void EncryptDecryptString(BOOL encrypt, const BYTE* data, DWORD dataSize, BYTE** result, DWORD* resultSize) {
HCRYPTPROV hProv = 0;
HCRYPTKEY hKey = 0;
HCRYPTHASH hHash = 0;
// Acquire a cryptographic provider context
if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
HandleError("Error during CryptAcquireContext!");
}
// Create a hash object
if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash)) {
HandleError("Error during CryptCreateHash!");
}
// Hash the password
const char* password = "secretpassword";
if (!CryptHashData(hHash, (BYTE*)password, (DWORD)strlen(password), 0)) {
HandleError("Error during CryptHashData!");
}
// Derive a session key from the hash object
if (!CryptDeriveKey(hProv, CALG_AES_256, hHash, 0, &hKey)) {
HandleError("Error during CryptDeriveKey!");
}
// Encrypt or decrypt the data
if (encrypt) {
// Calculate the required buffer size for the encrypted data
DWORD bufferSize = dataSize;
if (!CryptEncrypt(hKey, 0, TRUE, 0, NULL, &bufferSize, 0)) {
HandleError("Error during CryptEncrypt (size calculation)!");
}
// Allocate memory for the encrypted data
*result = (BYTE*)malloc(bufferSize);
memcpy(*result, data, dataSize);
*resultSize = dataSize;
// Encrypt the data
if (!CryptEncrypt(hKey, 0, TRUE, 0, *result, resultSize, bufferSize)) {
HandleError("Error during CryptEncrypt!");
}
} else {
// Decrypt the data
*resultSize = dataSize;
*result = (BYTE*)malloc(dataSize + 1);
memcpy(*result, data, dataSize);
if (!CryptDecrypt(hKey, 0, TRUE, 0, *result, resultSize)) {
HandleError("Error during CryptDecrypt!");
}
// Null-terminate the decrypted string
(*result)[*resultSize] = 0;
}
// Clean up
if (hHash) CryptDestroyHash(hHash);
if (hKey) CryptDestroyKey(hKey);
if (hProv) CryptReleaseContext(hProv, 0);
}
int main() {
const char* originalText = "hello, sailor!";
DWORD originalSize = (DWORD)strlen(originalText);
BYTE* encryptedData = NULL;
DWORD encryptedSize = 0;
// Encrypt the data
EncryptDecryptString(TRUE, (BYTE*)originalText, originalSize, &encryptedData, &encryptedSize);
printf("Encrypted data: ");
for (DWORD i = 0; i < encryptedSize; i++) {
printf("%02x", encryptedData[i]);
}
printf("\n");
BYTE* decryptedData = NULL;
DWORD decryptedSize = 0;
// Decrypt the data
EncryptDecryptString(FALSE, encryptedData, encryptedSize, &decryptedData, &decryptedSize);
printf("Decrypted data: %s\n", decryptedData);
// Free allocated memory
if (encryptedData) free(encryptedData);
if (decryptedData) free(decryptedData);
return 0;
}