c語(yǔ)言是一種非常強(qiáng)大的編程語(yǔ)言,在開發(fā)過(guò)程中經(jīng)常會(huì)用到j(luò)son數(shù)據(jù)格式。為了保護(hù)數(shù)據(jù)安全,我們通常會(huì)對(duì)json數(shù)據(jù)進(jìn)行加密處理,而c json加密就是其中一種方式。
#include <stdio.h> #include <cjson/cJSON.h> #include <string.h> #include <openssl/aes.h> #define AES_KEYLEN 256 #define AES_BLOCKLEN 16 unsigned char keys[AES_KEYLEN / 8] = { 0x51, 0x5A, 0x53, 0x36, 0x71, 0x45, 0x7D, 0x4B, 0x26, 0x53, 0x27, 0x61, 0x4C, 0x34, 0x72, 0x45, 0x75, 0x53, 0x67, 0x47, 0x3A, 0x6D, 0x25, 0x33, 0x34, 0x03, 0x96, 0xA7, 0x48, 0x5F, 0x1F, 0x38 }; unsigned char iv[AES_BLOCKLEN] = { 0x39, 0x29, 0x5C, 0x3D, 0x68, 0x56, 0x2E, 0x34, 0x3D, 0x2D, 0x53, 0x71, 0x34, 0x75, 0x3F, 0x28 }; int main(int argc, char ** argv){ char * plaintext = "{ \"name\":\"Tom\", \"age\":18, \"gender\":\"male\" }"; int len = strlen(plaintext); unsigned char* encrypted = (unsigned char*)malloc(len*sizeof(unsigned char)); memset(encrypted, 0, len*sizeof(unsigned char)); unsigned char* decrypted = (unsigned char*)malloc(len*sizeof(unsigned char)); memset(decrypted, 0, len*sizeof(unsigned char)); AES_KEY aes_key; AES_set_encrypt_key(keys, AES_KEYLEN, &aes_key); AES_cbc_encrypt((unsigned char*)plaintext, encrypted, len, &aes_key, iv, AES_ENCRYPT); AES_set_decrypt_key(keys, AES_KEYLEN, &aes_key); AES_cbc_encrypt(encrypted, decrypted, len, &aes_key, iv, AES_DECRYPT); printf("plaintext: %s\n", plaintext); printf("encrypted: %s\n", encrypted); printf("decrypted: %s\n", decrypted); free(encrypted); free(decrypted); return 0; }
以上示例代碼演示了如何使用OpenSSL C庫(kù)對(duì)JSON數(shù)據(jù)進(jìn)行加密。我們定義了AES密鑰和初始化向量,然后使用AES_cbc_encrypt函數(shù)執(zhí)行加密和解密操作。最后,我們輸出原始明文、加密后的密文和解密后的明文。
上一篇vue 怎么修改