Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read .p7m file using c#

Tags:

c#

.net

smime

how to retrieve all information for .P7M file using c# application. sample .p7m file : please if possible then give me code or sample example link

MIME-Version: 1.0
Content-Type: multipart/signed; protocol="application/x-pkcs7-signature"; micalg=sha1; boundary="----6975263937A7DDC0C0034052D76E8275"

This is an S/MIME signed message

------6975263937A7DDC0C0034052D76E8275
MIME-Version: 1.0
Subject: MVCI - Restart Needed a
X-Relevance-Evaluation-Period: 0:0:1
X-Relevance-Child-Evaluation-Period: 0:0:1
Content-Type: multipart/digest; boundary="AD27641"

--AD27641

Subject: MVCI - Restart Needed a
X-Relevant-When: pending restart and (not exists file "C:\Windows\System32\No_Reboot.txt")
X-Fixlet-ID: 27641
X-Fixlet-Category: Computer Support
X-Fixlet-Source: BigFix
X-Fixlet-Source-Severity: Moderate
X-Fixlet-Source-ID: <Unspecified>
X-Fixlet-Source-Release-Date: 9/12/2006
X-Fixlet-Download-Size: 0
Content-Type: multipart/related; boundary="F27641"

--F27641
Content-Type: text/html; charset=us-ascii

<custom>
--F27641
Content-id: Action1
Content-Type: application/x-Fixlet-Windows-Shell

// only run this action on computers that are not locked
continue if {not locked of action lock state}

restart
action requires restart

// only run this action on computers that are not locked
continue if {not locked of action lock state}

action parameter query "RestartWaitTime" with description "Please enter the number of seconds to wait after warning the user before forcing a restart on the computer:"

restart {parameter "RestartWaitTime" of action}
action requires restart

--F27641--

--AD27641--

------6975263937A7DDC0C0034052D76E8275
Content-Type: application/x-pkcs7-signature; name="smime.p7s"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="smime.p7s"

MIIC7QYJKoZIhvcNAQcCoIIC3jCCAtoCAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3
DQEHATGCArkwggK1AgEBMIIBXTCCAVYxCzAJBgNVBAYTAi0tMRQwEgYDVQQDEwtC
cmlhbiBKb25lczERMA8GA1UECBQIPE5PREFUQT4xETAPBgNVBAcUCDxOT0RBVEE+
MSUwIwYDVQQKExxNYXJyaW90dCBWYWNhdGlvbiBDbHViIEludCdsMQowCAYDVQQL
EwEtMSswKQYJKoZIhvcNAQkBFhxicmlhbi5qb25lc0B2YWNhdGlvbmNsdWIuY29t
MYGqMBAGA1UEKRMJSGFzaDpzaGExMDEGA1UEKRMqU2VydmVyOkxBTEZJTVZCRjEu
TVYuTUFSUkNPUlAuTUFSUklPVFQuQ09NMB0GA1UEKRMWTGljZW5zZUFsbG9jYXRp
b246NDk1MDAbBgNVBCkTFEN1c3RvbUFjdGlvbnM6RW5hYmxlMCcGA1UEKRMgQ3Vz
dG9tUmV0cmlldmVkUHJvcGVydGllczpFbmFibGUCARIwCQYFKw4DAhoFAKCBsTAY
BgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0wNjEwMTYx
ODE5MTRaMCMGCSqGSIb3DQEJBDEWBBRSsDje+FssF4dum8OfDyhrvlqYtjBSBgkq
hkiG9w0BCQ8xRTBDMAoGCCqGSIb3DQMHMA4GCCqGSIb3DQMCAgIAgDANBggqhkiG
9w0DAgIBQDAHBgUrDgMCBzANBggqhkiG9w0DAgIBKDANBgkqhkiG9w0BAQEFAASB
gOa3bY4oDVLwJ1LXv4YGJuWI7yrRnAPJu+CUJNB9VE40FVddLyZAgya4TtxVSxap
fB0/molXCbPcmG5eqNS8CZ/BPZtBbyTFai+hQNyhxSxvbvvn4xoCCtvftLj1UkVx
9ftCqSJKSeIWUk0jnQTU/pGrySOpXeJewqgRg06Sxejf

------6975263937A7DDC0C0034052D76E8275--

                                                                                                                                                                                                                                                                                                                            !÷Rž»¶ÛSccöê'˜az&¶¹C÷sˆâŒßjJÇIÓt*¶ók=;^ÀœË  ØMöšÐåÌù˜=pN…>á0'¶rjŠ"úžìŽä¨ýà˜Üðö<*%aÐ0êæS9䇓.$œG¿ˆÁWäà•)—L‡ënhQ'ú
ÎsÆRã±ùÎ"2A¾T¢ˆ³¿éy¢öK±–Ë'*Ì®  _%í#ÝRÖâÒÉX‰<u^N‡pÊ×DÚCóu°¼˜–E¢W•|^ç^e¢øákÎ؆@o¬ymíOX‚°žÏ\ƒhæ£F&Eô=´sx‹bÒ2!¢:¾Å¶œ¸¦€‡5Ž×ö$üd-CsÖðºHöNk+'.…š¡³à,§áßIŒ%œ”ð‹<$áÀ !hϸ¹!…*e´Ô(¯t¤u6 OÐKFLò™üå”!¿Õ„MÝ÷>Þ*yŽR:ÛOtÇüHeš3Ÿì‡~C0¥;L9‘ó0%ìû±Ò ¿no,e?‹õñcmO7ÒXZ*÷n­    ‘,ÈsÅç*ìE¡(§#\ãOax¬Ç¨’ˆøÞ¢™ÀçÌ*¸(^´-ùÝÍOä6Ø"‘Ù]ŒÕŒ¶R*‹†'ð˜ÅYŒìsˆ²’o[VáMûV•È%kÊNi5K8±–KÓ‡ÃeÈVk5·†lÆ7lŠü»¬ƒý΂ÃE[íD¡O)|Í —)#æó ÚübcÀv…€‰*¼‹5ó(ìÄtôù±ÐÔ^CS|T”f2£7ƲÕnÃDV_;?«Àþsy
2•^;=;002_tdqX¬«†@´iòQ‘TDª
2ªÀ4ªb(ä‹
 æöE8ý|,~ÊgU@÷eÉö•É£Spù í©L~T¢DÔÉÜcñ#”ˆ‚š]ƒ=ŽáïˆË9% RÒô3­UìIˆÁó}¨ÚîïÓºÁWÀ„;‚~ÒÇBæ#Íi}bI¤îh¾•2EŸ NÙüTâ÷;Ü1!T “¡2P¦q/+"G®LÙ)KÉÁ¤êR|…#UIÌgê¹Ý‚u¥°ç:#Í1ÝF7ŒPTB{ph882­–å“U$‹LÛù\œ¢êgõ\lGt˜¨æ˜Ph676µŸôÞÝ{ÝQU@Èn¤lT+'Þlô‹Å‚ž<5t„CÊl'ô”—ïí#×¹B]s©\òÀ`;ÚŠ‘ÆrÎäô7Ggg—zòÚ¸Þ;>;K~Å‘. o’’{X-˜É#•žM«nÛåhMò®[ž?h
ÒÉÿˆ´ßï`T@ìûv÷Æ´nä‹o}d¹†ÕŸ2k.•Fu…åNã]í$YÔµéŽz¾ÀPmÐúÔgù/3Ñã20õ¤‘zÆ‘/yzxñüìñ¿ž =[uþ F çW
Â%uÙGj¤‘…¡²¯¡‚®@®–úeñgù†¥F¶4v‘°ÑõÀŸ0Ýl`Ú@@0óçl¿Éø€¸Í
:ñ{çülCHÑĤœÔǦ<S¸[@À˜õ=}“ÙÍ‘±”±â=bYoãËKm?~A˜ô&kbhݸDuÔÿ½£ÙÿÙÙ£¯]¿&bÊüâY(@&ô€°fÕHæßÉTß–ß +|æ­ºQtÁYŠ«Š+‘Êû¼Ác4îµ{uiC¼œ¯4
”Dµ]^R
Œ.€8~wJì)N]“¥ûpÚv»Þ†¢øÔL5:[°¦|RÑ/gýÿ[öRÜáÜuÿçRR=€R—Œ¨7Ç&¯;?2:-¯í¹|lDšÑŽßÇÇ£Ù@P°¶žŸ¹xýhìÿ´*Ž‡`~£¤£2BŸ±W£óÚOøÒ$½u‰[Zgq\‚>ÇRÐýx$ŠYeW@çÀE¦Ë¨Dä}‘Ä2µ)Ä«`³afÙiõPèœüv¹y-Ž}}-¨Yˆ†iù¹[Þ#º¢ð<Üg–R÷ÚàÆ»KÀˆÔsÖD†DÂ
ñíìÆû´e¹Õ¸£ÑWÀ¼0À
Ð)Ñ.†ÝP
hÑõ¸À”“ë=$b¹ÍøÜÝùÍ¢Œ‡RñO][.ñ ‡Ð¼ogûº™€Íͼ@”=¼0‡Ð$õjÍÀ”Ú$ûœÚºäa‘PR+K¿¿ÊS zTZHmý•ß\òNø¸ý7àƒT:¥¿…ìõU·o35÷þµ£¡ÇÎÞë¿v_5+!Çhtïš'¿ÊzppY÷¦m™¸È‹Z‚Y’xdÊ‹ÔÚ™ðç¿¿«©ùl9%¦yeÖÞ·RvxKHG‘Òqô;(Óuá»JNô¡{AEþ}\9Ãý{ôYriþ‘FÏûr &„ò­ô€òU¢Òúkà¾&ƒ>žý€ibuJôžUOŒ¶“C€uIßçªg㉔r¾w”õYÚhŸ%dîáôÆò7Ÿe?ZЦd‰¸Àצê´lø”Oë™ëxâp

please give replay back if any suggetion and any quetion then tell me . i am waiting for replay .

like image 804
Dharmesh Hadiyal Avatar asked Jun 10 '14 09:06

Dharmesh Hadiyal


3 Answers

As an alternative to the non-free/non-open source solutions posted above, I might suggest taking a look at my free/open source S/MIME library: MimeKit

To handle your input data, you'd do something like this:

var entity = MimeEntity.Load (stream);

if (entity is MultipartSigned) {
    var signed = (MultipartSigned) entity;

    foreach (var signature in signed.Verify ()) {
        try {
            bool valid = signature.Verify ();

            // If valid is true, then it signifies that the signed content has
            // not been modified since this particular signer signed the content.
            //
            // However, if it is false, then it indicates that the signed content
            // has been modified.
        } catch (DigitalSignatureVerifyException) {
            // There was an error verifying the signature.
        }

        // If you'd like to get a copy of the certificate used for signing,
        // you could do this:
        var wrapper = (SecureMimeDigitalCertificate) signature.Certificate;
        var cert = wrapper.Certificate;

        // The cert is a BouncyCastle X509Certificate, so if you want to convert
        // it to a System.Security X509Certificate2, you can do this:
        var x509certificate2 = new X509Certificate2 (cert.GetEncoded ());
    }
}
like image 198
jstedfast Avatar answered Oct 21 '22 21:10

jstedfast


What you have is an S/MIME message. You need to parse the S/MIME message, then decode the attachment. .NET doesn't offer S/MIME parsing functionality out of the box, so you need to use some third-party library - either something mentioned in this answer or Rebex or our SecureBlackbox for parsing the message.

like image 33
Eugene Mayevski 'Callback Avatar answered Oct 21 '22 20:10

Eugene Mayevski 'Callback


please also check this way : more information related to code: http://www.logue.com.ar/blog/2010/03/encryption-and-decryption-with-x-509-certificates/

using System;
using System.Linq;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.IO;

namespace Logue.Library.Cryptography
{
public static class CryptographyHelper
{
    #region Public methods
    public static string Encrypt(string fullMessage, string certificateName)
    {
        X509Certificate2 certificate = GetCertificate(certificateName);

        string base64DecryptedContent = Convert.ToBase64String(Encoding.UTF8.GetBytes(fullMessage));
        base64DecryptedContent = ChunkContent(base64DecryptedContent, 76);
        base64DecryptedContent = EnvelopeBase64(base64DecryptedContent);

        byte[] contentBytes = Encoding.ASCII.GetBytes(base64DecryptedContent);

        Oid contentOid = new Oid("1.2.840.113549.1.7.1", "PKCS 7 Data");
        Oid algorithmOid = new Oid("1.2.840.113549.3.2", "rc2");
        AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(algorithmOid);
        ContentInfo content = new ContentInfo(contentOid, contentBytes);
        EnvelopedCms envelope = new EnvelopedCms(SubjectIdentifierType.NoSignature, content, algorithmIdentifier);

        envelope.Encrypt(new CmsRecipient(certificate));
        byte[] encryptedBytes = envelope.Encode();

        string encryptedContent = Convert.ToBase64String(encryptedBytes);

        encryptedContent = ChunkContent(encryptedContent, 76);
        string result = EnvelopEncryptedContent(encryptedContent);

        return result;
    }

    public static string Decrypt(string fullMessage)
    {
        string messageContent = GetContentInBase64(fullMessage);

        // Load envelope and decrypt
        EnvelopedCms envelope = new EnvelopedCms();
        envelope.Decode(Convert.FromBase64String(messageContent));
        envelope.Decrypt();

        // Get original bytes
        byte[] decryptedBytes = envelope.ContentInfo.Content;
        string decryptedText = Encoding.ASCII.GetString(decryptedBytes);

        // Get processed Base64 content
        byte[] decryptedContentBytes = Convert.FromBase64String(GetContentInBase64(decryptedText));
        string decryptedContentText = Encoding.UTF8.GetString(decryptedContentBytes);

        return decryptedContentText;
    }
    #endregion

    #region Private Methods
    private static string ChunkContent(string encryptedContent, int chunkSize)
    {
        StringBuilder sb = new StringBuilder();
        StringReader sr = new StringReader(encryptedContent);

        int position = 0;
        char[] buffer = new char[chunkSize];

        while (position < encryptedContent.Length)
        {
            if (encryptedContent.Length - (position + chunkSize) < 0)
            chunkSize = encryptedContent.Length - position;
            sb.Append(encryptedContent.Substring(position, chunkSize));
            sb.Append("rn");
            position += chunkSize;
        }

        return sb.ToString();
    }

    private static string EnvelopEncryptedContent(string encryptedContent)
    {
        return CryptographyResources.ENCRYPTED_TEMPLATE.Replace("[REPLACE]", encryptedContent);
    }

    private static string EnvelopeBase64(string content)
    {
        return CryptographyResources.BASE64_TEMPLATE.Replace("[REPLACE]", content);
    }

    private static X509Certificate2 GetCertificate(string certificateName)
    {
        X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
        X509Certificate2 certificate = store.Certificates.Cast<X509Certificate2>().Where(cert => cert.Subject.IndexOf(certificateName) >= 0).FirstOrDefault();
        if (certificate == null)
        throw new Exception("Certificate " + certificateName + " not found.");

        return certificate;
    }

    private static string GetContentInBase64(string fullMessage)
    {
        string contentSeparator = Environment.NewLine + Environment.NewLine;
        int startIndex = fullMessage.IndexOf(contentSeparator) + contentSeparator.Length;
        int endIndex = fullMessage.Length - 1;
        StringBuilder sb = new StringBuilder();
        string[] lines = fullMessage.Substring(startIndex, endIndex - startIndex).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
        foreach (string line in lines)
        sb.Append(line);
        return sb.ToString();
    }
    #endregion
}
}
like image 39
Dharmesh Hadiyal Avatar answered Oct 21 '22 19:10

Dharmesh Hadiyal