C语言怎样实现数据加密

发布时间:2025-02-15 00:50:36 作者:小樊
来源:亿速云 阅读:89

在C语言中实现数据加密,你可以使用一些现有的加密库,如OpenSSL、Crypto++等。下面是一个使用OpenSSL库进行简单数据加密和解密的例子。

首先,确保你已经安装了OpenSSL库。在Linux系统上,你可以使用以下命令安装:

sudo apt-get install libssl-dev

然后,创建一个名为encrypt.c的文件,并添加以下代码:

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

void handleErrors(void) {
    ERR_print_errors_fp(stderr);
    abort();
}

int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
            unsigned char *iv, unsigned char *ciphertext) {
    AES_KEY enc_key;
    int len;
    int ciphertext_len;

    if (!(len = AES_set_encrypt_key(key, 128, &enc_key)))
        handleErrors();

    ciphertext_len = 0;
    AES_cbc_encrypt(plaintext, ciphertext, plaintext_len, &enc_key, iv, AES_ENCRYPT);
    ciphertext_len = strlen((char *)ciphertext);

    return ciphertext_len;
}

int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
            unsigned char *iv, unsigned char *plaintext) {
    AES_KEY dec_key;
    int len;
    int plaintext_len;

    if (!(len = AES_set_decrypt_key(key, 128, &dec_key)))
        handleErrors();

    plaintext_len = 0;
    AES_cbc_encrypt(ciphertext, plaintext, ciphertext_len, &dec_key, iv, AES_DECRYPT);
    plaintext_len = strlen((char *)plaintext);

    return plaintext_len;
}

int main(int argc, char *argv[]) {
    unsigned char key[] = "abcdefghijklmnop";
    unsigned char iv[AES_BLOCK_SIZE];
    unsigned char plaintext[] = "This is a secret message";
    unsigned char ciphertext[128];
    unsigned char decryptedtext[128];
    int decryptedtext_len, ciphertext_len;

    if (argc != 3) {
        printf("Usage: %s <encrypt|decrypt> <text>\n", argv[0]);
        return 1;
    }

    if (!RAND_bytes(iv, AES_BLOCK_SIZE)) handleErrors();

    if (strcmp(argv[1], "encrypt") == 0) {
        ciphertext_len = encrypt(plaintext, strlen((char *)plaintext), key, iv, ciphertext);
        printf("Encrypted text:\n");
        for (int i = 0; i < ciphertext_len; i++)
            printf("%x", ciphertext[i]);
        printf("\n");
    } else if (strcmp(argv[1], "decrypt") == 0) {
        decryptedtext_len = decrypt(ciphertext, strlen((char *)ciphertext), key, iv, decryptedtext);
        decryptedtext[decryptedtext_len] = '\0';
        printf("Decrypted text:\n%s\n", decryptedtext);
    } else {
        printf("Error: %s\n", argv[1]);
        printf("Usage: %s <encrypt|decrypt> <text>\n", argv[0]);
        return 1;
    }

    return 0;
}

编译并运行这个程序:

gcc encrypt.c -lcrypto -o encrypt
./encrypt encrypt "Hello, World!"
./encrypt decrypt <encrypted_text>

这个例子使用了AES-128-CBC加密算法。你可以根据需要选择其他加密算法和密钥长度。注意,这个例子仅用于演示目的,实际应用中需要考虑更多的安全因素。

推荐阅读:
  1. C语言中怎么利用DES模块实现加密功能
  2. C语言中怎么利用AES模块实现加密功能

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c语言

上一篇:C语言如何进行代码调试

下一篇:C语言中类型转换要注意什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》