如何在 C 中使用 RSA 加密多个文件

How to encrypt multiple files using RSA in C

我用 C 编程语言使用 RSA 算法加密了一条消息。我想使用相同的密钥加密保存在特定文件夹中的多个文件。我在 openSSL 环境中工作。我用来加密特定消息的代码是

 // Get the message to encrypt
printf("Message to encrypt: ");
fgets(msg, KEY_LENGTH-1, stdin);
msg[strlen(msg)-1] = '[=10=]';

// Encrypt the message
encrypt = malloc(RSA_size(keypair));
int encrypt_len;
err = malloc(130);
if((encrypt_len = RSA_public_encrypt(strlen(msg)+1, (unsigned char*)msg, (unsigned char*)encrypt,
                                     keypair, RSA_PKCS1_OAEP_PADDING)) == -1) {
    ERR_load_crypto_strings();
    ERR_error_string(ERR_get_error(), err);
    fprintf(stderr, "Error encrypting message: %s\n", err);
    goto free_stuff;
}

现在我想使用 RSA 算法 来加密包含许多文件的文件夹,在 C[=19= 中使用相同的 public 密钥]

提前致谢!

您可以找到有关如何在基于 UNIX 的 Oses 中遍历目录的信息 in this SO question

如果您需要多平台的东西,也可以在 Whosebug 中找到 here

也许对您来说最好的建议是学习如何确定您的需求并进行一些好的研究。

您需要使用 opendirreaddir 函数打开一个目录并遍历其中的文件。然后对于每个文件名,检查它是否是常规文件,如果是则打开它并进行加密。

文件很可能会大于 RSA 密钥大小,因此您需要分段加密。

这是一个简单的例子:

void encrypt_files(char *dirname)
{
    DIR *dir;
    struct dirent *de;
    int rval;
    struct stat statbuf;
    FILE *f;

    if ((dir = opendir(dirname)) == NULL) {
        perror("Failed to open directory %s", dirname);
        return;
    }

    // always reset errno before calling readdir
    // otherwise a false error could be reported when you reach the end of the directory
    while ((errno = 0, de = readdir(dir)) != NULL) {
        rval = lstat(de->d_name, &statbuf);
        if (rval == -1) {
            perror("Error getting file status for %s", de->d_name);
            return;
        }
        if (S_ISREG(statbuf.st_mode)) {
            f = fopen(de->d_name, "r");
            if (f == NULL) {
                perror("Error opening file");
                return;
            }

            // read from f and encrypt

            fclose(f);
        }
    }
    closedir(dir); 
}