RSA加密的OpenSSL变长结果【C语言编程】

OpenSSL Variable Length Result for RSA Encryption [C programming]

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

我的RSA加密函数是:

/* 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] = '[=10=]';
   }

   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;
}

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

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

我知道没有填充的 RSA 是原始 RSA 加密,结果长度介于 0 和 n(RSA 位大小)之间 here 但我的代码使用 RSA_PKCS1_PADDING 所以我不确定为什么我仍然得到可变长度输出。

加密数据的长度在result中返回自:

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

encrypted返回的加密数据为二进制数据。你不能对它做一个 strlen 。数据不是 0 终止的,可能包含一些随机的 0。