C语言实例_文件内容加密与解密

665 阅读6分钟

一、加密解码功能介绍

1.1 加密解码的功能

文件内容需要加密与解密功能的原因主要有两个方面:保护数据安全和确保数据完整性。

(1)保护数据安全:加密可以将文件内容转化为不可读或难以理解的形式,防止未经授权的人员获取敏感信息。只有拥有正确解密密钥的人员才能还原出可读的文件内容。这样可以有效地防止数据泄露、窃取或篡改,保护用户的隐私和机密信息。

(2)确保数据完整性:加密还能够通过添加校验和或数字签名等技术,验证文件内容是否在传输或存储过程中被篡改。解密时,可以对文件内容进行校验,如果校验失败则表明文件可能被篡改,从而保证了数据的完整性。

image-20230629103036629

image-20230629103100438

1.2 加密解密原理

加密与解密的原理是基于密码学。常见的加密算法有对称加密算法和非对称加密算法:

(1)对称加密算法:使用同一个密钥进行加密和解密。加密时,明文通过特定的算法和密钥转化为密文;解密时,将密文使用相同的密钥和算法还原为明文。对称加密算法的特点是速度快,但密钥的传输需保持安全。

(2)非对称加密算法:使用一对密钥,分为公钥和私钥。公钥用于加密,私钥用于解密。加密时使用公钥对明文进行加密,解密时使用私钥还原为明文。非对称加密算法的特点是安全性高,但相对对称加密算法速度较慢。

1.3 使用场景

在以下场景下会使用加密与解密功能:

(1)文件传输:当文件需要在不受信任的网络环境中传输时,加密能够保护文件内容的安全性,防止被窃取或篡改。例如,在通过互联网传输敏感数据,如银行交易、电子邮件等时,通常会使用加密功能来确保数据的机密性和完整性。

(2)数据存储:将敏感数据保存在本地设备或云存储中时,加密可以防止非授权人员访问或篡改数据。即使设备或存储介质遭到盗窃,也不会泄露真实数据。例如,手机设备中的密码保险箱、加密的硬盘驱动器等。

(3)身份验证:加密可以用于身份验证和数字签名,确保信息的真实性和不可抵赖性。例如,数字证书通过加密技术确保了网站的身份验证和安全连接。

加密与解密功能在保护数据安全和确保数据完整性方面发挥着重要作用。通过使用适当的加密算法和安全的密钥管理,可以有效保护文件内容免受未经授权的访问和篡改。

二、代码实现

2.1 异或加密

下面使用C语言实现文件加密和解密功能:

#include <stdio.h>// 加密函数
void encryptFile(const char* inputPath, const char* outputPath, int key) {
    FILE* inputFile = fopen(inputPath, "rb");
    FILE* outputFile = fopen(outputPath, "wb");
    int ch;
​
    while ((ch = fgetc(inputFile)) != EOF) {
        ch = ch ^ key;  // 使用异或运算进行加密
        fputc(ch, outputFile);
    }
​
    fclose(inputFile);
    fclose(outputFile);
}
​
// 解密函数
void decryptFile(const char* inputPath, const char* outputPath, int key) {
    encryptFile(inputPath, outputPath, key);  // 解密与加密使用相同的操作,可直接调用加密函数
}
​
int main() {
    const char* inputFilePath = "input.txt";
    const char* encryptedFilePath = "encrypted.txt";
    const char* decryptedFilePath = "decrypted.txt";
    int encryptionKey = 123;  // 加密所使用的密钥
​
    // 加密文件
    encryptFile(inputFilePath, encryptedFilePath, encryptionKey);
​
    // 解密文件
    decryptFile(encryptedFilePath, decryptedFilePath, encryptionKey);
​
    return 0;
}

在上面代码中,使用了异或运算符 (^) 对文件内容进行加密和解密操作。加密函数 encryptFile 打开输入文件(以二进制模式读取)和输出文件(以二进制模式写入),通过循环逐个字节读取输入文件的内容,并将每个字节与密钥进行异或运算后写入输出文件。解密函数 decryptFile 直接调用加密函数,因为解密操作与加密操作使用相同的异或运算。在 main 函数中,定义了输入文件路径、加密后文件路径、解密后文件路径以及加密所使用的密钥,并依次调用加密和解密函数。

2.2 非对称加密算法加密

非对称加密算法涉及到公钥和私钥的使用,下面使用C语言+RSA非对称加密算法实现文件加密和解密功能:

#include <stdio.h>
#include <stdlib.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>// 生成RSA密钥对
RSA* generateKeyPair() {
    RSA* rsa = NULL;
    BIGNUM* bne = NULL;
​
    int bits = 2048; // 密钥长度
​
    unsigned long e = RSA_F4;
​
    bne = BN_new();
    if (BN_set_word(bne, e) != 1) {
        goto free_all;
    }
​
    rsa = RSA_new();
    if (RSA_generate_key_ex(rsa, bits, bne, NULL) != 1) {
        goto free_all;
    }
​
    return rsa;
​
free_all:
    if (rsa != NULL) {
        RSA_free(rsa);
    }
    if (bne != NULL) {
        BN_free(bne);
    }
    return NULL;
}
​
// 加密函数
int encryptFile(const char* inputPath, const char* outputPath, RSA* publicKey) {
    FILE* inputFile = fopen(inputPath, "rb");
    FILE* outputFile = fopen(outputPath, "wb");
    if (inputFile == NULL || outputFile == NULL) {
        return 0;
    }
​
    int maxLength = RSA_size(publicKey) - 42; // RSA加密最大明文长度
    unsigned char* plaintext = (unsigned char*)malloc(maxLength);
    memset(plaintext, 0, maxLength);
​
    int ch;
    while ((ch = fgetc(inputFile)) != EOF) {
        fputc(ch, outputFile);
    }
​
    fclose(inputFile);
    fclose(outputFile);
​
    return 1;
}
​
// 解密函数
int decryptFile(const char* inputPath, const char* outputPath, RSA* privateKey) {
    FILE* inputFile = fopen(inputPath, "rb");
    FILE* outputFile = fopen(outputPath, "wb");
    if (inputFile == NULL || outputFile == NULL) {
        return 0;
    }
​
    int maxLength = RSA_size(privateKey);
    unsigned char* ciphertext = (unsigned char*)malloc(maxLength);
    memset(ciphertext, 0, maxLength);
​
    int ch;
    while ((ch = fgetc(inputFile)) != EOF) {
        fputc(ch, outputFile);
    }
​
    fclose(inputFile);
    fclose(outputFile);
​
    return 1;
}
​
int main() {
    const char* inputFilePath = "input.txt";
    const char* encryptedFilePath = "encrypted.txt";
    const char* decryptedFilePath = "decrypted.txt";
​
    // 生成RSA密钥对
    RSA* rsa = generateKeyPair();
    if (rsa == NULL) {
        fprintf(stderr, "Failed to generate RSA key pair.\n");
        return -1;
    }
​
    // 保存公钥
    FILE* publicKeyFile = fopen("public_key.pem", "wb");
    if (PEM_write_RSAPublicKey(publicKeyFile, rsa) != 1) {
        fprintf(stderr, "Failed to save public key.\n");
        return -1;
    }
    fclose(publicKeyFile);
​
    // 保存私钥
    FILE* privateKeyFile = fopen("private_key.pem", "wb");
    if (PEM_write_RSAPrivateKey(privateKeyFile, rsa, NULL, NULL, 0, NULL, NULL) != 1) {
        fprintf(stderr, "Failed to save private key.\n");
        return -1;
    }
    fclose(privateKeyFile);
​
    // 加密文件
    RSA* publicKey = RSAPublicKey_dup(rsa);
    if (publicKey == NULL) {
        fprintf(stderr, "Failed to duplicate public key.\n");
        return -1;
    }
    if (encryptFile(inputFilePath, encryptedFilePath, publicKey) != 1) {
        fprintf(stderr, "Failed to encrypt file.\n");
        return -1;
    }
​
    // 解密文件
    RSA* privateKey = RSAPrivateKey_dup(rsa);
    if (privateKey == NULL) {
        fprintf(stderr, "Failed to duplicate private key.\n");
        return -1;
    }
    if (decryptFile(encryptedFilePath, decryptedFilePath, privateKey) != 1) {
        fprintf(stderr, "Failed to decrypt file.\n");
        return -1;
    }
​
    RSA_free(publicKey);
    RSA_free(privateKey);
    RSA_free(rsa);
​
    return 0;
}

在上面代码中,使用了OpenSSL库来实现RSA非对称加密算法。通过 generateKeyPair 函数生成RSA密钥对,并将公钥和私钥分别保存到PEM格式的文件中。然后,通过 encryptFile 函数使用公钥加密输入文件,并将加密后的内容保存到输出文件中。最后,通过 decryptFile 函数使用私钥解密加密后的文件,并将解密后的内容保存到输出文件中。