Problem with gcry_pk_decrypt (libgcrypt)

Claudia Reuter reuter at
Wed Aug 3 14:33:57 CEST 2005

Hi @ll.

I like to encrypt and decrypt large files e.g. pdf files. I wrote some
code based on libgcrypt. I tested it with .txt files. Encryption seems
to work, but gcry_pk_decrypt works only, if there's a single line in the
txt file. If the txt file contains more than one line of text, the
result is wrong. But no error occurs.

/** Start encryption */

//read data block
InputFile.seekg (0, ios::end);
int FileSize = InputFile.tellg();
InputFile.seekg (0, ios::beg);

char* Buffer;
Buffer = new char[FileSize];,FileSize);

//build S-Expression
char fmt[] = "(data (flags raw) (value %s))";

char* strSExp = (char *) malloc(strlen(Buffer)+strlen(fmt));
sprintf(strSExp, fmt, (va_list) Buffer);

rc = gcry_sexp_build(&sexp, NULL, fmt, strSExp);

// Encrypt plaintext
rc = gcry_pk_encrypt(&result, sexp, pKey);

// Write it to file
size_t retSize = gcry_sexp_sprint(result, GCRYSEXP_FMT_ADVANCED, NULL, 0);
strSExp = (char *) realloc(strSExp, retSize);
retSize = gcry_sexp_sprint(result, GCRYSEXP_FMT_ADVANCED, strSExp, retSize);
fwrite( &retSize, 1 , sizeof(retSize) , OutputFile );
fwrite( strSExp , 1 , retSize , OutputFile );

/** End encryption */

/** Start decryption */
//read size
fread(&retSize, 1, sizeof(retSize), InputFile);
//read encrypted text
Buffer = (char *) malloc(retSize);
fread(Buffer, 1, retSize, InputFile);

rc = gcry_sexp_new(&sexp, Buffer, 0, 1);
rc = gcry_pk_decrypt(&result, sexp, sKey);

/** End decryption */

After that rc is 0 and result is like that

Any help would be appreciated.

Yours Claudia

More information about the Gnupg-users mailing list