在C語言中,實現(xiàn)數(shù)據(jù)的加密和解密通常需要使用一些加密算法
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
void xor_encrypt(char *data, int key) {
for (int i = 0; i < strlen(data); i++) {
data[i] ^= key;
}
}
int main() {
char data[] = "Hello, World!";
int key = 42;
printf("Original data: %s\n", data);
// 加密數(shù)據(jù)
xor_encrypt(data, key);
printf("Encrypted data: %s\n", data);
// 解密數(shù)據(jù)
xor_encrypt(data, key);
printf("Decrypted data: %s\n", data);
return 0;
}
這個例子中,我們使用了一個簡單的異或加密算法。請注意,這種加密方法并不安全,僅適用于演示目的。在實際應(yīng)用中,建議使用更安全的加密庫,如OpenSSL。
要使用OpenSSL庫進(jìn)行加密和解密,你需要安裝OpenSSL并鏈接到你的項目。然后,可以使用OpenSSL提供的EVP系列函數(shù)進(jìn)行加密和解密操作。這里是一個使用AES-256-CBC模式的加密和解密示例:
#include<openssl/evp.h>
#include<openssl/rand.h>
#include<string.h>
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext) {
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
if (!(ctx = EVP_CIPHER_CTX_new())) {
return -1;
}
if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)) {
EVP_CIPHER_CTX_free(ctx);
return -1;
}
if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) {
EVP_CIPHER_CTX_free(ctx);
return -1;
}
ciphertext_len = len;
if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) {
EVP_CIPHER_CTX_free(ctx);
return -1;
}
ciphertext_len += len;
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key, unsigned char *iv, unsigned char *plaintext) {
EVP_CIPHER_CTX *ctx;
int len;
int plaintext_len;
if (!(ctx = EVP_CIPHER_CTX_new())) {
return -1;
}
if (1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)) {
EVP_CIPHER_CTX_free(ctx);
return -1;
}
if (1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) {
EVP_CIPHER_CTX_free(ctx);
return -1;
}
plaintext_len = len;
if (1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) {
EVP_CIPHER_CTX_free(ctx);
return -1;
}
plaintext_len += len;
EVP_CIPHER_CTX_free(ctx);
return plaintext_len;
}
int main() {
unsigned char key[32];
unsigned char iv[16];
unsigned char plaintext[] = "Hello, World!";
unsigned char ciphertext[128];
unsigned char decrypted_text[128];
int ciphertext_len;
int decrypted_text_len;
// 生成隨機(jī)密鑰和初始化向量
RAND_bytes(key, sizeof(key));
RAND_bytes(iv, sizeof(iv));
// 加密數(shù)據(jù)
ciphertext_len = encrypt(plaintext, strlen((char *)plaintext), key, iv, ciphertext);
if (ciphertext_len == -1) {
printf("Encryption failed\n");
return 1;
}
// 解密數(shù)據(jù)
decrypted_text_len = decrypt(ciphertext, ciphertext_len, key, iv, decrypted_text);
if (decrypted_text_len == -1) {
printf("Decryption failed\n");
return 1;
}
decrypted_text[decrypted_text_len] = '\0';
printf("Original text: %s\n", plaintext);
printf("Decrypted text: %s\n", decrypted_text);
return 0;
}
這個示例使用了AES-256-CBC模式進(jìn)行加密和解密。請注意,在實際應(yīng)用中,密鑰和初始化向量應(yīng)該從安全的源生成,而不是使用隨機(jī)數(shù)生成器。