The RSA OpenSSL C ++ character is different from the command line character

I am trying to sign text in C ++ and then check it on the command line. I am using OpenSSL libraries. This is my command line for generating keys:

openssl genrsa -out key.pem 1024

Now I have my secret key. Then here is how I can execute the command on the command line:

echo "hola" | openssl rsautl -pkcs -sign -inkey key.pem > sign.txt

At this point, everything works, as it seems, now I have a sign in sign.txt. Now I'm trying to do the same in C ... This is my code:

RSA * rsaPrivKey;


RSA * createRSAWithFilename (const char * filename, int publicKey)
{
   FILE * fp = fopen (filename, "rb");

   if (fp == NULL)
   {
      printf ("Unable to open file %s \n", filename);
      return NULL;
   }
   RSA *rsa = RSA_new ();

   if (publicKey)
      rsa = PEM_read_RSA_PUBKEY (fp, &rsa, NULL, NULL);
   else
      rsa = PEM_read_RSAPrivateKey (fp, &rsa, NULL, NULL);

   return rsa;
}


void initRSA (void)
{
   rsaPrivKey = createRSAWithFilename ("key.pem", 0);

   unsigned char text[] = {"hola"};
   unsigned char encrypted[4098] = {};
   unsigned int outlen;

   unsigned char hash[20];
   if (!SHA1 (text, sizeof(text), hash)){
      printf ("SHA1 failed\n");
      exit (0);
   }
   if (!RSA_sign (NID_sha1, hash, 20, encrypted, &outlen, rsaPrivKey)){
      printf ("RSA_sign failed\n");
      exit (0);
   }

   printf ("Result:\n");
   for (int a = 0; a < outlen; a++)
      printf ("%c", encrypted[a]);

   exit (1);
}

When I call initRSA (), it prints the generated signature .. but .. it's not the same as the one generated on the command line.

Because I’m not sure if sizeof accepts the real length of the “text”, I tried with length = 4 (hola has 4 characters) and 5 (possibly computing \ 0), and the results are not expected.

. , .

+4
1

-, , . , :

echo -n "hola" | openssl dgst -sha1 -binary -sign key.pem >sign.txt

pkeyutl , : C openssl dgst, rsautl

, ( echo -n, ) sizeof(text)-1, , .

+4

Source: https://habr.com/ru/post/1616632/


All Articles