static void Main(string[] args)
 {
     loadPfx();
     if (args[0].Equals("write"))
     {
         DistributionEnvelope d = DistributionEnvelope.newInstance();
         d.addRecipient(null, "test:address:one");
         d.setService("dotnet:test:service");
         d.addRecipient("1.2.826.0.1285.0.2.0.107", "123456789012");
         d.addIdentity("1.2.826.0.1285.0.2.0.107", "99999999999");
         d.addSender(null, "test:address:two");
         d.setInteractionId("test_interaction_UK01");
         for (int i = 1; i < args.Length; i++)
         {
             // Álternate MIME type and file name
             String mt = args[i++];
             String file = args[i];
             String body = null;
             byte[] content = null;
             Payload p = new Payload(mt);
             //bool pack = (i != 2);
             bool pack = true;
             if (mt.Contains("xml"))
             {
                 body = load(file);
                 if (!pack)
                 {
                     p.setProfileId("itk:test:profile-id-v1-0");
                 }
                 p.setBody(body, pack);
             }
             else
             {
                 content = binaryLoad(file);
                 p.setContent(content, pack);
             }
             d.addPayload(p);
             p.addReaderCertificate(cert1);
     //                    p.addReaderCertificate(cert2);
             p.encrypt(sgpk, sgcert);
         }
         String expout = d.ToString();
     }
     else
     {
         String inde = load(args[1]);
         DistributionEnvelopeHelper helper = DistributionEnvelopeHelper.getInstance();
         DistributionEnvelope de = helper.getDistributionEnvelope(inde);
         Payload[] p = helper.getPayloads(de);
         if (p[0].isEncrypted())
         {
             helper.unpackEncryptedPayload(p[0]);
             if (p[0].hasKeyForReader("CN=test102.oneoneone.nhs.uk, OU=ITK Accreditation Services, O=National Integration Centre"))
             {
                 String firstpayload = p[0].decryptTextContent("CN=test102.oneoneone.nhs.uk, OU=ITK Accreditation Services, O=National Integration Centre", cert1.PrivateKey);
             }
         }
         else
         {
             String x0 = p[0].getContent();
             String x1 = p[1].getContent();
         }
         String x = p[0].getBody();
     }
 }
        public void unpackEncryptedPayload(Payload p)
        {
            // Run an XSL transform to extract from the PayloadBody:
            //
            // 1. The encrypted keys as N=keyname####K=base64encodedkey pairs
            // 2. A "payload delimiter" (static)
            // 3. The base64 encoded ciphertext
            //
            // Get that as a text string, then split it up and add it to the
            // Payload
            StringWriter extractBuffer = new StringWriter();
            XmlTextWriter extractWriter = new XmlTextWriter(extractBuffer);
            StringReader sr = new StringReader(p.getBody());
            XmlTextReader rdr = new XmlTextReader(sr);
            encryptedDataExtractor.Transform(rdr, extractWriter);

            String[] parts = extractBuffer.GetStringBuilder().ToString().Split(PAYLOAD_DELIMITER, StringSplitOptions.None);
            if (parts.Length != 2) {
                throw new Exception("Malformed EncryptedData");
            }
            p.setEncryptedContent(parts[1]);

            // Parse out the encrypted symmetric keys and add them to the Payload
            //
            String[] r = parts[0].Split(PAYLOAD_FIELD_DELIMITER, StringSplitOptions.None);
            String keyname = null;
            String encryptedkey = null;
            for (int i = 1; i < r.Length; i++) {
                if (r[i].StartsWith("KEYNAME:=")) {
                    keyname = r[i].Substring(9);
                    i++;
                    if (r[i].StartsWith("ENCRYPTEDKEY:=")) {
                        encryptedkey = r[i].Substring(14);
                        p.addReceivedReader(keyname, encryptedkey);
                    } else {
                        throw new Exception("Malformed EncryptedData - encrypted key value expected but not found");
                    }
                } else {
                    throw new Exception("Malformed EncryptedData - key name expected but not found");
                }
            }
        }
        private Payload[] splitPayloads(String s)
        {
            String id = null;
            String mt = null;
            String pid = null;
            String b64 = null;
            String cmpd = null;
            String enc = null;
            String pbdy = null;

            String[] parts = s.Split(PAYLOAD_DELIMITER, StringSplitOptions.RemoveEmptyEntries);
            Payload[] payloads = new Payload[parts.Length];
            int i = 0;
            foreach (String p in parts)
            {
                String[] fields = p.Split(PAYLOAD_FIELD_DELIMITER, StringSplitOptions.RemoveEmptyEntries);
                foreach (String f in fields)
                {
                    String[] element = f.Split(EQUALS_DELIMITER, StringSplitOptions.None);
                    if (element[0].Equals("ID"))
                    {
                        id = element[1];
                        continue;
                    }
                    if (element[0].Equals("MIMETYPE"))
                    {
                        mt = element[1];
                        continue;
                    }
                    if (element[0].Equals("PROFILEID"))
                    {
                        if (element.Length == 2)
                        {
                            pid = element[1];
                        }
                        continue;
                    }
                    if (element[0].Equals("BASE64"))
                    {
                        if (element.Length == 2)
                        {
                            b64 = element[1];
                        }
                        else
                        {
                            b64 = "false";
                        }
                        continue;
                    }
                    if (element[0].Equals("COMPRESSED"))
                    {
                        if (element.Length == 2)
                        {
                            cmpd = element[1];
                        }
                        else
                        {
                            cmpd = "false";
                        }
                        continue;
                    }
                    if (element[0].Equals("ENCRYPTED"))
                    {
                        if (element.Length == 2)
                        {
                            enc = element[1];
                        }
                        else
                        {
                            enc = "false";
                        }
                        continue;
                    }
                    if (element[0].Equals("PAYLOADBODY"))
                    {
                        pbdy = element[1];
            //                        pbdy = pbdy.Remove(pbdy.LastIndexOf(PAYLOAD_DELIMITER[0]));
                        continue;
                    }
                }
                payloads[i] = new Payload(id, mt, pid, b64, cmpd, enc);
                payloads[i].setContent(pbdy);
                i++;
            }
            return payloads;
        }
 /**
  *  Adds a pre-build Payload instance.
  */
 public void addPayload(Payload p)
 {
     if (payloads == null){
         payloads = new List<Payload>();
     }
     payloads.Add(p);
 }