Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <openssl/conf.h>
- #include <openssl/evp.h>
- #include <openssl/err.h>
- void handleErrors(void)
- {
- ERR_print_errors_fp(stderr);
- abort();
- }
- int decryptFile(const char *inputFile, const char *outputFile, const char *passphrase)
- {
- OpenSSL_add_all_algorithms();
- ERR_load_crypto_strings();
- FILE *inFile = fopen(inputFile, "rb");
- if (!inFile) {
- perror("Error opening input file");
- return 1;
- }
- FILE *outFile = fopen(outputFile, "wb");
- if (!outFile) {
- perror("Error opening output file");
- fclose(inFile);
- return 1;
- }
- const EVP_CIPHER *cipher = EVP_aes_256_cbc();
- const EVP_MD *digest = EVP_sha256();
- unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH];
- unsigned char salt[8] = {0};
- fread(salt, 1, 8, inFile); // skip Salted__
- fread(salt, 1, 8, inFile); // store next 8 bytes
- if (!EVP_BytesToKey(cipher, digest, salt, (const unsigned char *)passphrase,
- strlen(passphrase), 1, key, iv)) {
- #if 0
- if (!EVP_BytesToKey(cipher, digest, NULL, (const unsigned char *)passphrase, strlen(passphrase), 1, key, iv)) {
- #endif
- perror("Error deriving key and IV");
- fclose(inFile);
- fclose(outFile);
- return 1;
- }
- EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
- if (!ctx) {
- perror("Error creating context");
- fclose(inFile);
- fclose(outFile);
- return 1;
- }
- if (1 != EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv)) {
- perror("Error initializing decryption");
- EVP_CIPHER_CTX_free(ctx);
- fclose(inFile);
- fclose(outFile);
- return 1;
- }
- EVP_CIPHER_CTX_set_padding(ctx, 0);
- unsigned char inBuf[1024], outBuf[1024];
- int bytesRead, decryptedLen;
- while ((bytesRead = fread(inBuf, 1, sizeof(inBuf), inFile)) > 0) {
- if (1 != EVP_DecryptUpdate(ctx, outBuf, &decryptedLen, inBuf, bytesRead)) {
- perror("Error updating decryption");
- EVP_CIPHER_CTX_free(ctx);
- fclose(inFile);
- fclose(outFile);
- return 1;
- }
- fwrite(outBuf, 1, decryptedLen, outFile);
- }
- if (1 != EVP_DecryptFinal_ex(ctx, outBuf, &decryptedLen)) {
- ERR_print_errors_fp(stderr);
- perror("Error finalizing decryption");
- EVP_CIPHER_CTX_free(ctx);
- fclose(inFile);
- fclose(outFile);
- return 1;
- }
- fwrite(outBuf, 1, decryptedLen, outFile);
- EVP_CIPHER_CTX_free(ctx);
- fclose(inFile);
- fclose(outFile);
- return 0;
- }
- int main()
- {
- const char *inputFile = "encrypted_file.enc";
- const char *outputFile = "decrypted_file.txt";
- const char *passphrase = "111111";
- if (decryptFile(inputFile, outputFile, passphrase) == 0) {
- printf("File decrypted successfully.\n");
- } else {
- fprintf(stderr, "Error decrypting file.\n");
- }
- ERR_free_strings();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement