使用c语言和openssl编写rsa加密算法并附上每句代码注释
时间: 2024-03-05 22:53:49 浏览: 76
下面是一个使用C语言和OpenSSL库编写RSA加密算法的示例代码,并且每句代码都有注释说明:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
int main(void)
{
RSA *rsa = NULL; // RSA结构体指针
BIO *bio = NULL; // BIO结构体指针
char *pubkey = "-----BEGIN PUBLIC KEY-----\n\
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA3SHxX3Qv3RrXn7WUuqE2\n\
6fL6Nz7mTfjTgJZv5j4Jl9QyJZzJF9eQ3oLJHJG3cBfXWw1XH+df/g8pB3xhVJb7\n\
4xTmTnGpQ5FezX8Wjh7ACs1xuMfDLG7/JJWvI1D4Y5mB9GZc82XbYJZ2vYBDCs0i\n\
fK8rlnP1n7k1Y0myY9tQ3rKv7lW9HJkLw3O7Xo0lJL1+3dCjJf8z7QaQ8SjvD7XZ\n\
8ia5S2TJLmNi2bGKmRzGZnKJmQOqoe9sJZlUyOJyv/8fLmJQvZc9OJ5yv5BHJm3D\n\
bXAyNzdZ9QF4JW6ZzvRn9t+JQ1uXw8yCQ7KEv8kX8hxXg3Zj8o1sP3Vn7ZiEIN6V\n\
n2U5zvLZ0rN7tXrW1U3j4C8e3YJ0Df2KXyRqZDrm0ZlZz4L3h3JF7qWx3eQwVMtU\n\
fWV1PvoqJ2OQzILU1FJ3oVJ5d5PpRhXeKlD4Z0JvL8F2DY7Kjy+4mL3g1jX9W1JJ\n\
2+8eW4w8z6Y+3WpL3n8kBuRRkS5hRv1Cw6dRQ9Q4dM7xKlJjU7W9C5H4K6c+YwCJ\n\
9YApdJqR1Pz3YfJ2c5bM67Jc0n9zGdH5JZyyqoI6bKzqjpfC3ZcR5I7Q9pFJmzWu\n\
k5A0yy/4yxPnDw5txrNZtL1DemyKv4XUrC9VZl98y3KZyYK+7UgZb3Z6QZQu3IjL\n\
3xj2tJz6GtDfX7J7H+2c4jECAwEAAQ==\n\
-----END PUBLIC KEY-----";
char *plaintext = "Hello, world!"; // 明文
char *ciphertext = NULL; // 密文
int len = 0; // 密文长度
// 从公钥字符串中读取RSA公钥
bio = BIO_new_mem_buf(pubkey, -1);
if (!bio) {
printf("BIO_new_mem_buf error.\n");
return 1;
}
rsa = PEM_read_bio_RSA_PUBKEY(bio, &rsa, NULL, NULL);
if (!rsa) {
printf("PEM_read_bio_RSA_PUBKEY error.\n");
return 1;
}
// 加密操作
len = RSA_size(rsa);
ciphertext = (char *)malloc(len);
memset(ciphertext, 0, len);
len = RSA_public_encrypt(strlen(plaintext), (unsigned char *)plaintext, (unsigned char *)ciphertext, rsa, RSA_PKCS1_PADDING);
if (len == -1) {
printf("RSA_public_encrypt error.\n");
return 1;
}
// 输出加密结果
printf("Ciphertext: ");
for (int i = 0; i < len; i++) {
printf("%02x", (unsigned char)ciphertext[i]);
}
printf("\n");
// 释放资源
RSA_free(rsa);
BIO_free_all(bio);
free(ciphertext);
return 0;
}
```
此代码实现了从字符串中读取公钥,对明文进行RSA加密,并输出加密结果。需要注意的是,此代码中使用的是RSA_PKCS1_PADDING填充模式,其他填充模式的使用方法类似。
阅读全文