RSA加密的OpenSSL可变长度结果[C编程] [英] OpenSSL Variable Length Result for RSA Encryption [C programming]

查看:232
本文介绍了RSA加密的OpenSSL可变长度结果[C编程]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用OpenSSL的RSA加密功能对一些文本进行加密.我的主要问题是,加密的RSA文本的长度在0到256之间变化.

I am trying to encrypt some text using OpenSSL's RSA encryption functions. My main issue is that the length of the encrypted RSA text varies between 0 and 256.

我的RSA加密功能是:

My RSA encryption function is:

/* Encrypt data using RSA */
char* rsa_encrypt(char* pub_key_filename, const unsigned char *data)
{
   int padding = RSA_PKCS1_PADDING;

   FILE *fp_pub;
   fp_pub = fopen(pub_key_filename, "rb");

   if (fp_pub == NULL)
   {
      printf("There was an error opening the public key file. Exiting!\n");
      exit(EXIT_FAILURE);
   }

   RSA *pub_key = PEM_read_RSA_PUBKEY(fp_pub, NULL, NULL, NULL);

   char *encrypted = malloc(2048);
   int i;
   for (i = 0; i < (2048); i++)
   {
      encrypted[i] = '\0';
   }

   int result = RSA_public_encrypt(strlen(data), data, encrypted, pub_key, padding);
   if (result == -1)
   {
      printf("There was an error during RSA encryption.\n");
      return "ERROR_RSA_ENCRYPTION";
   }

   fclose(fp_pub);

   return encrypted;
}

以下代码涉及尝试加密一些文本:

The following code involves trying to encrypt some text:

const unsigned char *key = (unsigned char *)"abcdefghijklmnopqrstuvwxyzabcdef";
unsigned char *encrypted_aes_key = rsa_encrypt("public.pem", key);

我知道没有填充的RSA是原始RSA加密,并且产生的长度在0到n(RSA位大小)之间,如

I know that RSA with no padding is primitive RSA encryption and the resulting length is between 0 and n (RSA bit size) as seen here but my code is using RSA_PKCS1_PADDING so I am not sure why I am still getting variable length output.

推荐答案

result中从以下位置返回加密数据的长度:

The length of the encrypted data is returned in result from:

int result = RSA_public_encrypt(strlen(data), data, encrypted, pub_key,填充);

encrypted中返回的加密数据是二进制数据.你不能为此感到惊讶.数据不是以0结尾的,并且其中可能包含一些随机0.

The encrypted data returned in encrypted is binary data. You can't do a strlen on it. The data is not 0 terminated and might contain some random 0 in it.

这篇关于RSA加密的OpenSSL可变长度结果[C编程]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆