openssl中的rsa代码
时间: 2023-10-24 19:23:44 浏览: 114
以下是使用 OpenSSL 库进行 RSA 加密和解密的示例代码:
```c
#include <openssl/rsa.h>
#include <openssl/pem.h>
RSA *createRSA(unsigned char *key, int public)
{
RSA *rsa = NULL;
BIO *keybio;
keybio = BIO_new_mem_buf(key, -1);
if (keybio == NULL)
{
printf("Failed to create key BIO\n");
return NULL;
}
if (public)
{
rsa = PEM_read_bio_RSA_PUBKEY(keybio, &rsa, NULL, NULL);
}
else
{
rsa = PEM_read_bio_RSAPrivateKey(keybio, &rsa, NULL, NULL);
}
return rsa;
}
int public_encrypt(unsigned char *data, int data_len, unsigned char *key, unsigned char *encrypted)
{
RSA *rsa = createRSA(key, 1);
int result = RSA_public_encrypt(data_len, data, encrypted, rsa, RSA_PKCS1_PADDING);
return result;
}
int private_decrypt(unsigned char *enc_data, int data_len, unsigned char *key, unsigned char *decrypted)
{
RSA *rsa = createRSA(key, 0);
int result = RSA_private_decrypt(data_len, enc_data, decrypted, rsa, RSA_PKCS1_PADDING);
return result;
}
```
使用示例:
```c
unsigned char publicKey[] = "-----BEGIN PUBLIC KEY-----\n"
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDP7v2MjGjD3XxK2nFJQun5ZC0\n"
"mL6nH6Jd3auwAhVQYV9x2Kv1w1K1hE9aJm4Lb0dKXrNLi9q8jyQGGd6y2jZy8sE\n"
"eC9I2v9Qv3s2r1yv0D6vB6QJ1aIkh8tZu6p8s7vRQ3t4oScnNj8mJQfY3LQD8b1\n"
"uI1NjG5QOcQGvUwUWwIDAQAB\n"
"-----END PUBLIC KEY-----\n";
unsigned char privateKey[] = "-----BEGIN PRIVATE KEY-----\n"
"MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAM/u/YyMaMPdfEr\n"
"acUlC6flkLSYvqcfol3dq7ACFVBhX3HYq/XDUrWET1ombgtvR0pek0uL2ryPJA\n"
"YZ3rLaNnLywR4L0ja/1C/ezavXK/QPq8HpAnVoiSHy1m7qnyzu9FDe3ihJyc2P\n"
"yYlB9jctAPxvW4jU2MblA5xABr1MFJsBAgMBAAECgYEAh/jvJU0RmNwLjL4aBNG\n"
"z2Dzv6+D1pdLT7alV8mzgK6vZs7fN1g5zWzC8x6rZoJmPq6+1zL9+8j7cGX6O7m\n"
"n1VPk7LQJAdZbZM2oHJ9+1OoFfZGpA3j+9wmuUxkQwzn3wBfGwJb8Yj6r6V6Hx2\n"
"y7j2Cg1pR6w1Qb1mFkQI/6K5T8mE+Lm2W+4J1fNQaIb8W8qX3cCQQDfVBn3j2W4\n"
"hU7mDn7zYgQFpW6m3T3tOu+kXvVpKkZd0Wj8AmxAQrBv+9QAbCzT5JLnzvR+2Nl\n"
"XcBn2UcZAkEA3jNqT7m4dGQ8y5dMnDdsfBmD8lCj3yUZUWvKcT6OS8u9tY8f1q8\n"
"T9HJvJ9f5tBz8lNz8ZLlS7I8FZ6dGwDn6wJBAM+9Y9b1N4y0k6Pw7D7z0PqJh7A\n"
"AP3jvZv3Ib6Nt1LZ4a/mhZuL+0HrH3xwvXgWbL2r6j7NkM8yjJLJcEiWvEkCQDfH\n"
"HgEgy3w7S4fXj7c+u4NUbV9D5VdLm5WmQg8oEj7zJ+UVtG0kxWpH496+G7aWgHt\n"
"r8e3NqXzq1qJv9JCbRUCQH8GvZ1WcJF0XF7S1Kg/5L7X9Qd/7d5QO1QOeT3oY5u\n"
"5D8s6YjHHu9bJNK5A5QkqnKX8kXzGJdJ0qCJZ0EJqYs=\n"
"-----END PRIVATE KEY-----\n";
int main()
{
char *msg = "Hello World!";
unsigned char encrypted[4098] = {0};
unsigned char decrypted[4098] = {0};
int encrypted_length = public_encrypt((unsigned char *)msg, strlen(msg), publicKey, encrypted);
int decrypted_length = private_decrypt(encrypted, encrypted_length, privateKey, decrypted);
printf("Original Message: %s\n", msg);
printf("Encrypted Message: %s\n", encrypted);
printf("Decrypted Message: %s\n", decrypted);
return 0;
}
```
此示例将“Hello World!”字符串加密并解密,然后输出原始消息,加密消息和解密消息。注意,此代码仅是示例,实际使用时需要更严格的错误处理。
阅读全文