我需要做一些RSA解密,我的私钥存储在一个文件中。 我正在使用C ++。 起初我使用的是OpenSSL,它工作顺利,但随后出现了许可问题,因为我希望我的代码与GPLv2兼容。现在我正在尝试使用libgcrypt,但是我在使用S表达式时遇到了问题。这是我的代码:
#include <stdio.h>
#include <stdint.h>
#include <iostream>
#include <gcrypt.h>
using namespace std;
int main()
{
int cipher_len, key_len;
FILE *t = NULL, *k = NULL;
gcry_mpi_t text_mpi = NULL;
gcry_sexp_t text_s_exp = NULL;
gcry_mpi_t key_mpi = NULL;
gcry_sexp_t key_s_exp = NULL;
gcry_sexp_t decrypted_s_exp = NULL;
gcry_error_t err;
/* read encrypted text file */
if( ! ( t = fopen( "outrsa", "rb" ) ) )
{
cout << "could not open encrypted text file" << endl;
goto error;
}
fseek( t, 0, SEEK_END );
cipher_len = ftell( t );
rewind( t );
uint8_t text[cipher_len];
memset( text, '\0', cipher_len );
fread( text, 1, cipher_len, t );
if( ferror( t ) )
{
cout << "error while reading encrypted text file" << endl;
goto error;
}
/* create S-expression for encrypted text */
if( gcry_mpi_scan( &text_mpi, GCRYMPI_FMT_USG, text, cipher_len, NULL ) )
{
cout << "error when scanning mpi from encrypted file text" << endl;
goto error;
}
if( gcry_sexp_build( &text_s_exp, NULL, "(enc-val(flags oaep)(rsa(a %m)))", text_mpi ) )
{
cout << "error while creating S-expr from mpi for encrypted text" << endl;
goto error;
}
/* read private key file */
if( ! ( k = fopen( "priv.key", "rb" ) ) )
{
cout << "could not open key file" << endl;
goto error;
}
fseek( k, 0, SEEK_END );
key_len = ftell( k );
rewind( k );
uint8_t key[key_len];
memset( key, '\0', key_len );
key_len = fread( key, 1, key_len, k );
if( ferror( k ) )
{
cout << "error while reading key file" << endl;
goto error;
}
/* create S-expression for private key */
if( gcry_mpi_scan( &key_mpi, GCRYMPI_FMT_USG, key, key_len, NULL ) )
{
cout << "error when scanning mpi from key file" << endl;
goto error;
}
if( gcry_sexp_build( &key_s_exp, NULL, "(data(flags raw)(value %m))", key_mpi ) )
{
cout << "error while creating S-expr from mpi for key" << endl;
goto error;
}
/* decrypt */
if( ( err = gcry_pk_decrypt( &decrypted_s_exp, text_s_exp, key_s_exp ) ) )
{
cout << "error on decryption, source: " << gcry_strsource( err ) << ", error: " << gcry_strerror( err ) << endl;
goto error;
}
/* extract decrypted text from S-expr */
unsigned char decrypted[ cipher_len + 1 ];
memset( decrypted, '\0', cipher_len + 1 );
if( gcry_sexp_sprint( decrypted_s_exp, GCRYSEXP_FMT_DEFAULT, decrypted, cipher_len ) )
{
cout << "error while extracting decrypted text from S-expr" << endl;
goto error;
}
cout << "decrypted text:" << endl << decrypted << endl;
return 0;
error:
if( text_mpi )
gcry_mpi_release( text_mpi );
if( key_mpi )
gcry_mpi_release( key_mpi );
if( text_s_exp )
gcry_sexp_release( text_s_exp );
if( key_s_exp )
gcry_sexp_release( key_s_exp );
if( decrypted_s_exp )
gcry_sexp_release( decrypted_s_exp );
if( k )
fclose( k );
if( t )
fclose( t );
return 1;
}
现在,我知道这肯定不是使用libgcrypt的正确方法(因为我正在将整个关键文本作为MPI读取,并且解密失败),但是在前面的手册中,我找不到一种阅读方式钥匙... 我应该手动解析密钥吗?
谢谢!