Signed Mails (not encrypted) with smime.p7m - c#

I try to extract one ore more PDF Files from a Signed Mail. Simply i tryed to load the smime.p7m with
mimeMessage = MimeMessage.Load(mem);
//mem is a MemoryStream from File created with File.WriteAllBytes(file,fileAttachment.Content); (EWS FileAttachment)
This is not working, because the File begins with:
0€ *†H†÷
 €0€10 + 0€ *†H†÷
 €$€‚
&Content-Type: multipart/mixed;
boundary="----=_NextPart_000_0024_01D432F9.7988F010"
So i removed the shit (not all here visible) before Content-Type (with IndexOf, Substring) .. now i can load it into a MineMessage. Now i try to decode the Base64 String, but if i use the decodeto Method the Filesize is nearly the Same
but File is damaged, if i look in the Raw Data of the Original PDF File decoded by Outlook and my decoded one, they are nearly the same but in the last 10% they are different (in the original are more Linebreaks).
So i tryed to use
Convert.FromBase64String()
But i get allways invalied base64 code exception
the PDF Part with header begins with:
Content-Type: application/pdf;
name="DE_Windows 7_WebDAV.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="WebDAV.pdf"
‚ JVBERi0xLjUNCiW1tbW1DQoxIDAgb...
(before and after the , are not here visible Chars, i removed them too). If i load the base64 Code (copy&Paste as Text, with Windows Editor) into a onlinedecoder its is decoding, if i upload the File with the base64code it fails ...
AND inside the base64 are some not base64 chars "unknown" ,"," "Uparrow Symbol", i think this will kill the decoding, the base64 code is too long for here =( (see picture)
But this ist 1:1 what File.WriteAllBytes(file,fileAttachment.Content); or/and fileAttachment.Load(file); saves
Can u help me please? And from where are this unknown Chars?

Ok, i got it ... 2 Days of my Life wasted for this ***
Before saving a signed Attachment u must run this code to "unsign" and all the chars u not want are gone =)
byte[] content = fileAttachment.Content;
var signed = new SignedCms();
signed.Decode(content);
byte[] unsigned = signed.ContentInfo.Content;

Related

load screenshot from adb through c#

I want to get a screenshot into c# using adb without saving files to the filesystem all the time.
I'm using the SharpAdbClient to talk with the device.
I'm on a windows platform.
This is what i got so far:
AdbServer server = new AdbServer();
StartServerResult result = server.StartServer(#"path\to\adb.exe", restartServerIfNewer: false);
DeviceData device = AdbClient.Instance.GetDevices().First();
ConsoleOutputReceiver receiver = new ConsoleOutputReceiver();
AdbClient.Instance.ExecuteRemoteCommand("screencap -p", device, receiver);
string str_image = receiver.ToString().Replace("\r\r", "");
byte[] bytes = Encoding.ASCII.GetBytes(str_image);
Image image = Image.FromStream(new MemoryStream(bytes));
I can successfully load both str_image, and create the byte array but it keeps saying System.ArgumentException when trying to load it into an Image.
I also tried saving the data to a file, but the file is corrupt.
I tried both replacing "\r\r" and "\r\n", both same result.
Anyone has some insight in how to load this file?
It's actually preferred if it could be loaded into a Emgu image since i'm gonna do some CV on it later.
One possible cause is the nonprintable ASCII characters in the string.
Look at the code below
string str_image = File.ReadAllText("test.png");
byte[] bytes = Encoding.ASCII.GetBytes(str_image);
byte[] actualBytes = File.ReadAllBytes("test.png");
str_image is shown in the below screencap, note that there are some non-printable chars (displayed as question mark).
The first eight bytes of a PNG file are always
137 80 78 71 13 10 26 10
While you read the console output as a string, then use ASCII to encode the string, the first byte becomes 63 (0x3F), which is the ASCII code for a question mark.
Also note that the size of the two byte arrays vary hugely (7828/7378).
And other thing is you are replace "\r\r", while actually a new line character in Windows is "\r\n".
So my conclusion is some image data is lost or modified in the output redirection by the ConsoleOutputReceiver, and you cannot recover the original data from the output string.

c# System.Security.Cryptography.X509Certificates.X509ContentType.Cert is this DER?

How can I be sure that my exported certificate file is DER encoded?
Is there a way to check the file?
I can export a certificate loaded into memory to a file
string strFilename = _rksvpath + cert.GetSerialNumberString() + ".cer";
byte[] bytesCertExport = cert.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert);
File.WriteAllBytes(strFilename, bytesCertExport);
and the file is OK, which I can prove with certutil
C:\>certutil -dump C:\temp\0104A73D4557FCE026120AC356.cer
X.509-Zertifikat:
Version: 3
Seriennummer: 0104a73d4557fce026120ac356
Signaturalgorithmus:
Algorithmus Objekt-ID: 1.2.840.113549.1.1.11 sha256RSA
Algorithmusparameter: 05 00
...
However, I can not find any information about the encoding in the output of certutil, or in the windows certificate-viewer (opened with below command)
"C:\Windows\system32\rundll32.exe" cryptext.dll,CryptExtOpenCER C:\temp\0104A73D4557FCE026120AC356.cer
X.509 certificates are always encoded by using Distinguished Encoding Rules (DER).
The only difference is how DER value is stored in the file, either an exact binary copy or when binary data is encoded by using Base64. Standard tools do not tell what file format is used (binary, or Base64). You can read the first byte of the file. If it is ASCII 48, then the file is exact binary copy of the certificate, otherwise, binary copy is base64-encoded with or without PEM header/footer.

Failure to convert JFIF/Jpeg from CardDAV server's response

I'm using C#'s WebClient to download and image from a CardDav server and when I look at Fiddler the response from the server will contain a jpeg file, I can even preview the response as an image on Fiddler and it looks fine.
I've tried all the c# conventional methods to convert byte arrays to image/bitmap and none of them work, they throw an "invalid argument exception" exception.
FIDDLER response preview:
Content-Type: image/jpeg
Cache-Control: max-age=32000000, private
Content-Disposition: attachment
Content-Length: 46341
ÿØÿà JFIF ÿÛ C ÿÛ CÿÀ œ ² ÿÄ
ÿÄ µ } !1AQa"q2‘¡#B±ÁRÑð$3br‚
%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚáâãäåæçèéêñòóôõö÷øùúÿÄ
ÿÄ µ w !1AQaq"2B‘¡±Á #3RðbrÑ
$4á%ñ&'()56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz‚ƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚâãäåæçèéêòóôõö÷øùúÿÚ ? ÿ ?ú (  €
(Ü>~οiïX|9øà=[âŒ5ËK(4}È{¥k¸¯®ÃÃ$É3YÙéú^©ªêw0E2iºN™¨jw¾M•œó êì…ÿ &ý©ièüq{¯jºÁµøo«Ieâ_
øâË]³ñµäz–½¦Þbøoû1µ©e¹»ðÖ­§é­£Í£^ëË¢6¡·¥ëú^‘š‹Kvíøú
®Á¼:f™û,káü¿þ(~Ô><ñ=æƒðÏÂÞ4Ó"ø/¥Úivþ¹Ôõ=w^Ò¼A¯yö+¢^Xj?b:Ô–/­ØCe|šVÛäµµI÷ð«öcý†>3|hý®¼9û2.™¦øOÆÖþ3—C½»ñî­]ø&ÛZЊê'Iñ,iot¶wðÂ>ݦ]Åm©­Œ—\XGx¯fvM¾‰¿¸ôý™?fKŸÙãàφ¾~Îqi¿ üsñ7Bñ'íà¿|HøÉ¢i%øà8í<;âü>Õ<3â2ø]|Cðźèþ›sqáýà³ð]íí‘Õ¾ÚéwÊ´\d£Ì›M'¦­ýCk?Äÿ
ø‡Æ^"¸øÉñ<|ÃÚ7ˆuÙüpøû7ŽnõO é/™l-õýGâÑ黨øœk~ ¹Ò5]2ïQ“Á^Ò5“EƒW’æ![•Z|Òv²{ëÑ¿.þ›þw_ðUOØ+Dz'í6“ÿ ÷„-´¿‰vkã
ø/ៈu xÃú•êé>ðä:®¥¿¾žâK[ˆàžðIu}qò=î©ró]?Dd¤®¿¯ëüÀýý™¿à߯|Tý›ü¯|cÅ?
Format: JPEG
46,341 bytes
178w x 156h
1.67 bytes/px
96 dpi
Baseline
Subsample#4:4:4 (non-opt)
APP0 Data (14 bytes)
[JFIF1.1]
Aspect: 1:1
HuffmanTables: 4
SOLUTION
It seems like in my WebClient routine I was pushing some necessary headers that caused the image to be returned in a strange encoding, now I'm pushing only "User-Agent" and "Authorization" and the response can be decoded to image perfectly.
It seems like in my WebClient routine I was pushing some unnecessary headers that caused the image to be returned in a strange encoding, now I'm pushing only "User-Agent" and "Authorization" and the response can be decoded into an image perfectly.

Exchange Web Services - convert emailitem attachment from Base64 string to Byte gives error

I am trying to read an email item attachment using EWS and save it to disk as a text file so it can be used later on.
I am getting an error:
"The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters. "
here is my code:
Directory.CreateDirectory(emailAttachmentsPath);
// Put attachment contents into a stream. C:\Dev\EWSHelloWorld
emailAttachmentsPath = emailAttachmentsPath + "\\" + sEmailSubject+".txt";
//save to disk
using (Stream FileToDisk = new FileStream(emailAttachmentsPath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
byte[] ContentBytes = System.Convert.FromBase64String(itemAttachment.ToString());
FileToDisk.Write(ContentBytes, 0,ContentBytes.Length);
FileToDisk.Flush();
FileToDisk.Close();
}
what is the best way to do this please?
I basically want the text of the email in a text file, and any attachments in that email would be saved to disk as well (I can do that part I think using FileStream.
Philip,
You will not be able to use the Convert() method on an ItemAttachment because it is not Base64 encoded. The item attachment has a lot of properties about the item, and if I understand your request properly you are looking for just the body of the email.
The first thing you will want to consider is adding a check to see if the ItemAttachment is an email message. If it is, there are couple of lines to get to the text of the email body:
itemAttachment.Load(new PropertySet(BasePropertySet.FirstClassProperties));
string BodyText = itemAttachment.Item.Body.Text;
The first line will load the item and it's first class properties. The second line will get the text version of the email body.
I hope this helps. If this does resolve your question, please mark the post as answered.
Thanks,
--- Bob ---

PDF content inside XML response file

I receive XML file that includes PDF content:
<pdf>
<pdfContent>JVBERi0xLjQKJaqrrK0KNCAwIG9iago8PCAvV.......
How can I save the content into PDF file?
I'm using C# 4.0
That string value is the PDF in base64. If you convert the base64 to a byte array you can just write that byte array to disk.
Convert.FromBase64String
var buffer = Convert.FromBase64String(xmlStringValue);
File.WriteAllBytes(yourFileName, buffer);
It looks like the pdf content is encoded in base64. You will have to decode it and save it to a file.
Edit: indeed, when I use base64 to encode a pdf file, the first few characters are JVBERi0x...
It seems encoded with Base64, But not sure. if it is, you can take that long string and convert with the function Convert.FromBase64. You will obtain a byte[] that you can save as the actual pdf.

Categories