예제 #1
0
        public static MessageModel EncryptMessage(this MessageModel message)
        {
            if (message.Recipient != null && message.Recipient.PublicKey == null)
            {
                return(message);
            }

            // Serialize the message
            MemoryStream stream = new MemoryStream();

            ProtoBuf.Serializer.Serialize <MessageModel>(stream, message);

            // Encrypt it using AES
            byte[] aesKey;
            byte[] encryptedSerializedMessage = AesEncryption.EncryptMessage(stream.ToArray(), out aesKey);

            // Encrypt the AES key using sender's Public Key and recipient's public key
            byte[] senderEncryptedKey    = RsaEncryption.EncryptMessage(aesKey, message.Sender.PublicKey);
            byte[] recipientEncryptedKey = RsaEncryption.EncryptMessage(aesKey, message.Recipient.PublicKey);

            // Put them together to create an encrypted message
            MemoryStream encryptedMessageBytes = new MemoryStream();

            encryptedMessageBytes.WriteBlob(recipientEncryptedKey);
            encryptedMessageBytes.WriteBlob(senderEncryptedKey);
            encryptedMessageBytes.WriteBlob(encryptedSerializedMessage);

            // Copy only the minimal amount of data
            MessageModel encryptedMessage = new MessageModel();

            encryptedMessage.EncryptedMessage = encryptedMessageBytes.ToArray();
            encryptedMessage.MessageFlags     = MessageFlags.EncryptedMessage;
            message.CopyNonEncryptedProperties(encryptedMessage);

            encryptedMessage.ClientMessageId = message.ClientMessageId;

            return(encryptedMessage);
        }