一个 Linux下非对称加密demo,ubuntu18.04验证通过
-
生成密钥对:
openssl genrsa -out private_key.pem 2048 openssl rsa -in private_key.pem -outform PEM -pubout -out public_key.pem
#include <stdio.h> #include <string.h> #include <openssl/rsa.h> #include <openssl/pem.h> int main() { // 加载RSA密钥对 RSA *rsa_keypair = RSA_new(); FILE *private_key_file = fopen("private_key.pem", "r"); PEM_read_RSAPrivateKey(private_key_file, &rsa_keypair, NULL, NULL); fclose(private_key_file); // 加载公钥 RSA *rsa_public_key = RSA_new(); FILE *public_key_file = fopen("public_key.pem", "r"); PEM_read_RSA_PUBKEY(public_key_file, &rsa_public_key, NULL, NULL); fclose(public_key_file); // 明文数据 char *plaintext = "Hello, world!"; // 分配内存保存加密后的数据 int plaintext_len = strlen(plaintext); int encrypted_len = RSA_size(rsa_public_key); unsigned char *encrypted_data = (unsigned char *)malloc(encrypted_len); // 加密数据 int result = RSA_public_encrypt(plaintext_len, (unsigned char *)plaintext, encrypted_data, rsa_public_key, RSA_PKCS1_PADDING); if (result == -1) { printf("Error: RSA_public_encrypt failed!\n"); return -1; } // 输出加密后的数据 printf("Encrypted data: "); for (int i = 0; i < result; i++) { printf("%02x", encrypted_data[i]); } printf("\n"); // 分配内存保存解密后的数据 int decrypted_len = RSA_size(rsa_keypair); unsigned char *decrypted_data = (unsigned char *)malloc(decrypted_len); // 解密数据 result = RSA_private_decrypt(encrypted_len, encrypted_data, decrypted_data, rsa_keypair, RSA_PKCS1_PADDING); if (result == -1) { printf("Error: RSA_private_decrypt failed!\n"); return -1; } // 输出解密后的数据 printf("Decrypted data: %s\n", decrypted_data); // 释放内存 free(encrypted_data); free(decrypted_data); RSA_free(rsa_keypair); RSA_free(rsa_public_key); return 0; }
编译指令:
gcc -o rsa_example rsa_example.c -lcrypto
运行:
./rsa_example Encrypted data: 831bbcc94a2f5b30b605849d4756273b7d88d4995f2a2688f26aab81ef3ab992e7fcebe0530e8c0d5c4f889313648f319d55e2321d48edec4e1760959ca24b168 2d0e06911c3e1f8e94357f10b88f2fd6a0e3b1978a8ce6252de849d410f36b1123d7a4a66913eb1bd6c8096fb80f15bda150530a77f6aace39008f35bf7873d11a4903fa0d97647a6 18630b7781732a81d72e17771c60cf343b18565f1e49422dcd2de33cb4f18693a1def0c9b029ec6d1b96991bde6e55b3bdd972391df3c403c13fe27b38df75b4aeb963ad34cd0d55b 26f810d0735017c0e93da288c12bcf71a9b08cacee9923843a506585b534b484ef63119fe813dbf90b9c85fd707ef Decrypted data: Hello, world!
Copyright © 2024 深圳全志在线有限公司 粤ICP备2021084185号 粤公网安备44030502007680号