S/MIME - PKCS7_sign output via i2d_PKCS7_bio_stream is corupted?

André Weber WeberAndre at gmx.de
Fri Aug 19 12:10:05 UTC 2022


Hello,

(Sorry for posting as HTML Mail;)
 
I'am writing a mailing solution with S/MIME support - especially with signing the messages.
Usually I would use the following code sequence to geht the MIME encoded message body.
(I'am working with Delphi and OpenSSL 1.1.1q)
 
//  ---- First try --
PBIO InputBioFile   := BIO_new_file('c:\mySourceMail.txt','rb');
PBIO OutputBioFile := BIO_new_file('c:\mySingedMail.txt','wb');
flags := 0;
p7 := PKCS7_sign( FCertificate, FPrivateKey, nil, InputBioFile, flags );
SMIME_write_PKCS7( OutputBioFile, p7, InputBioFile, flags );
PKCS7_free(p7);
BIO_Free(InputBioFile);
BIO_Free(OutputBioFile );
//  ----
output is in the case the ready to use mimeblock, but in my case I need
the binary version of the "p7m" data, because codebase for mailing will
encode this its own base64 encoder.
 
// so I tried this
// -- Second try -- getting binary p7m file --
//
PBIO InputBioFile   := BIO_new_file('c:\mySourceMail.txt','rb');
PBIO OutputBioFile := BIO_new_file('c:\smime.p7m','wb');
flags := PKCS7_BINARY or PKCS7_STREAM;
p7 := PKCS7_sign( FCertificate, FPrivateKey, nil, InputBioFile, flags );
i2d_PKCS7_bio_stream( OutputBioFile, p7, InputBioFile, flags )
PKCS7_free(p7);
BIO_Free(InputBioFile);
BIO_Free(OutputBioFile );
// ---
 
To check myself I decoded the Mimedata from the first function to the smime.p7m file,
and compared this with the output from the second try --- I KNOW that there is a lot
of binarydata which I can't compare - but the also contained "mySourceMail.txt" should
be the same in both files I assume. But this isn't the case the file from the second try
ist slightly larger than the first and contains some random bytes at every 4k of data.
Verfication of the sigature fails for that.
 
I think the problem may arise from useing the PKCS7_STREAM flag, but without only
the signature is written to the output - and not the data?
 
In i2d_ASN1_bio_stream() the flag PKCS7_STREAM leads to SMIME_crlf_copy(..) that
will try to copy the source directly to the dest (PKCS7_BINARY) which just reads 1k and
writes 1k ...  the output is buffered through BIO_f_buffer() which uses a 4k buffer ...
may be the buffering is buggy? so that the data gets corrupted every 4k?
 
 
Any idea or hints are welcome ...
 
André Weber
 



More information about the openssl-users mailing list