encrypt of firmwire

#include <openssl/evp.h>
#include <openssl/rand.h>
#include <stdio.h>
#include <string.h>

// Encrypts the content of the input file `arg1` and writes the encrypted content to the output file `arg2`.
// The encryption is performed using AES-256-CBC with a salted key derived from the passphrase `arg3`.
// Returns 1 on success and 0 on failure.
int32_t saltedEncrypt(char* arg1, char* arg2, char* arg3) {
FILE *inputFile = fopen(arg1, "rb");
if (inputFile == NULL) {
puts("Failed to open input file");
return 0;
}

FILE *outputFile = fopen(arg2, "wb");
if (outputFile == NULL) {
puts("Failed to create output file");
fclose(inputFile);
return 0;
}

const EVP_CIPHER *cipherType = EVP_aes_256_cbc();
unsigned char salt[8];
if (RAND_bytes(salt, sizeof(salt)) != 1) { // Generate a random salt.
puts("Failed to generate salt");
fclose(inputFile);
fclose(outputFile);
return 0;
}

// Writing the "Salted__" magic string and the salt to the output file.
fwrite("Salted__", 1, 8, outputFile);
fwrite(salt, 1, sizeof(salt), outputFile);

unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH];
// Derive the key and IV from the passphrase and salt using SHA-256.
if (!EVP_BytesToKey(cipherType, EVP_sha256(), salt, (unsigned char*)arg3, strlen(arg3), 1, key, iv)) {
puts("Failed to generate key");
fclose(inputFile);
fclose(outputFile);
return 0;
}

EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL || EVP_EncryptInit_ex(ctx, cipherType, NULL, key, iv) != 1) {
puts("Encryption initialization failed");
EVP_CIPHER_CTX_free(ctx);
fclose(inputFile);
fclose(outputFile);
return 0;
}

unsigned char inBuf[1024], outBuf[1024 + EVP_MAX_BLOCK_LENGTH];
int inLen, outLen;
while ((inLen = fread(inBuf, 1, sizeof(inBuf), inputFile)) > 0) {
if (EVP_EncryptUpdate(ctx, outBuf, &outLen, inBuf, inLen) != 1) {
handleErrors(); // Define your error handling function.
// Exit or cleanup resources.
}
fwrite(outBuf, 1, outLen, outputFile);
}

if (EVP_EncryptFinal_ex(ctx, outBuf, &outLen) != 1) {
handleErrors(); // Handle errors appropriately.
// Exit or cleanup resources.
}
fwrite(outBuf, 1, outLen, outputFile);

EVP_CIPHER_CTX_free(ctx);
fclose(inputFile);
fclose(outputFile);

return 1; // Success.
}

Contact form