在Android开发中,有许多不同的加密算法可供选择。其中一种最常用且方便的加密算法是AES(Advanced Encryption Standard),它支持128位、192位和256位密钥长度。

以下是一个示例,展示了如何在Native层的C++代码中使用AES加密和解密一个文件:

#include <openssl/aes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define AES_BLOCK_SIZE 16

void encryptFile(const char* inputFile, const char* outputFile, const char* key) {
    FILE* inFile = fopen(inputFile, "rb");
    FILE* outFile = fopen(outputFile, "wb");

    if (inFile == NULL || outFile == NULL) {
        printf("Failed to open file.\n");
        return;
    }

    fseek(inFile, 0, SEEK_END);
    long fileSize = ftell(inFile);
    fseek(inFile, 0, SEEK_SET);

    unsigned char* fileBuffer = (unsigned char*)malloc(fileSize);
    fread(fileBuffer, 1, fileSize, inFile);

    unsigned char iv[AES_BLOCK_SIZE];
    memset(iv, 0x00, AES_BLOCK_SIZE);

    AES_KEY aesKey;
    AES_set_encrypt_key((const unsigned char*)key, 128, &aesKey);

    unsigned char encryptedBuffer[fileSize];
    AES_cbc_encrypt(fileBuffer, encryptedBuffer, fileSize, &aesKey, iv, AES_ENCRYPT);

    fwrite(encryptedBuffer, 1, fileSize, outFile);

    fclose(inFile);
    fclose(outFile);

    free(fileBuffer);
}

void decryptFile(const char* inputFile, const char* outputFile, const char* key) {
    FILE* inFile = fopen(inputFile, "rb");
    FILE* outFile = fopen(outputFile, "wb");

    if (inFile == NULL || outFile == NULL) {
        printf("Failed to open file.\n");
        return;
    }

    fseek(inFile, 0, SEEK_END);
    long fileSize = ftell(inFile);
    fseek(inFile, 0, SEEK_SET);

    unsigned char* fileBuffer = (unsigned char*)malloc(fileSize);
    fread(fileBuffer, 1, fileSize, inFile);

    unsigned char iv[AES_BLOCK_SIZE];
    memset(iv, 0x00, AES_BLOCK_SIZE);

    AES_KEY aesKey;
    AES_set_decrypt_key((const unsigned char*)key, 128, &aesKey);

    unsigned char decryptedBuffer[fileSize];
    AES_cbc_encrypt(fileBuffer, decryptedBuffer, fileSize, &aesKey, iv, AES_DECRYPT);

    fwrite(decryptedBuffer, 1, fileSize, outFile);

    fclose(inFile);
    fclose(outFile);

    free(fileBuffer);
}

int main() {
    const char* inputFile = "input.txt";
    const char* encryptedFile = "encrypted.bin";
    const char* decryptedFile = "decrypted.txt";
    const char* key = "0123456789abcdef";

    encryptFile(inputFile, encryptedFile, key);
    decryptFile(encryptedFile, decryptedFile, key);

    printf("Encryption and decryption completed.\n");

    return 0;
}

在上面的示例中,我们使用了OpenSSL库中的AES函数来实现加密和解密。在encryptFile函数中,我们打开输入文件和输出文件,读取输入文件的内容到缓冲区中,然后使用AES_set_encrypt_key函数设置密钥,并使用AES_cbc_encrypt函数对文件内容进行加密。加密后的结果写入输出文件。

在decryptFile函数中,我们执行类似的操作,但是使用AES_set_decrypt_key函数设置密钥,并使用AES_cbc_encrypt函数对文件内容进行解密。解密后的结果写入输出文件。

请注意,此示例仅用于展示如何在Native层的C++代码中使用AES加密和解密文件。在实际应用中,您可能需要更多的错误处理和安全措施


原文地址: https://www.cveoy.top/t/topic/irUq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录