byte[] EncodeMessage(byte[] recipient_pubkey, byte[] msgid, byte[] replyTo, string txt, byte[] prvkey, byte[] pubkey, out byte[] aes_key, out byte[] aes_iv) { if (replyTo == null) replyTo = new byte[16]; var txtbuf = Encoding.UTF8.GetBytes(txt); var SignMessage = prvkey != null; byte[] hash = null; if (SignMessage) { using (var rsa = new RSACryptoServiceProvider()) { RSAParameters rsap; Shared.LoadKey2(Shared.prvToPem(prvkey), null, out rsap); rsa.ImportParameters(rsap); using (var ms = new MemoryStream()) //sign { ms.Write(msgid, 0, msgid.Length); ms.Write(replyTo, 0, replyTo.Length); ms.WriteShort((short)txtbuf.Length); ms.Write(txtbuf, 0, txtbuf.Length); ms.WriteShort((short)pubkey.Length); ms.Write(pubkey, 0, pubkey.Length); ms.WriteShort((short)recipient_pubkey.Length); ms.Write(recipient_pubkey, 0, recipient_pubkey.Length); ms.Position = 0; hash = rsa.SignData(ms, SHA512OID); } } } byte[] c1; using (var ms1 = new MemoryStream()) using (var ms = new BZip2OutputStream(ms1)) { ms.Write(txtbuf, 0, txtbuf.Length); ms.Close(); c1 = ms1.ToArray(); } var compressText = c1.Length < txtbuf.Length; byte[] aesmsg; using (var aes = new RijndaelManaged()) { using (MemoryStream msEncrypt = new MemoryStream()) { using (var encryptor = aes.CreateEncryptor()) using (CryptoStream sw2 = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { aes_key = aes.Key; aes_iv = aes.IV; sw2.WriteByte((Byte)((compressText ? 1 : 0) | (SignMessage ? 2 : 0))); sw2.Write(msgid, 0, msgid.Length); sw2.Write(replyTo, 0, replyTo.Length); if (compressText) { sw2.WriteShort((short)c1.Length); sw2.Write(c1, 0, c1.Length); } else { sw2.WriteShort((short)txtbuf.Length); sw2.Write(txtbuf, 0, txtbuf.Length); } if (SignMessage) { sw2.WriteShort((short)pubkey.Length); sw2.Write(pubkey, 0, pubkey.Length); sw2.WriteShort((short)hash.Length); sw2.Write(hash, 0, hash.Length); } } msEncrypt.Flush(); aesmsg = msEncrypt.ToArray(); } } return aesmsg; }