Exemplo n.º 1
0
        public EncryptedMessage Encrypt(string messageText, int recieverId)
        {
            if (messageText == null)
            {
                throw new ArgumentException("Message text cannot be null");
            }

            IContactModel receiverContact = _storageService.GetContacts().FirstOrDefault(c => c.Id == recieverId);

            if (receiverContact == null)
            {
                throw new ArgumentException("Contact with id of receiverId does not exist");
            }

            EncryptedMessage encMsg = new EncryptedMessage();
            AesCipher        aes    = new AesCipher();

            // set initiazlization vector
            encMsg.Iv = FormatConverter.BytesToString64(aes.IV);

            // enccrypt message text symmetrically
            byte[] messageBytes          = FormatConverter.StringToBytes(messageText);
            byte[] encryptedMessageBytes = aes.Encrypt(messageBytes);
            encMsg.Body = FormatConverter.BytesToString64(encryptedMessageBytes);

            // encrypt symmetric key with receivers public key
            string    receiverPublicKey = receiverContact.PublicKey;
            RsaCipher rsa = new RsaCipher(receiverPublicKey);

            byte[] encryptedSymmetricKeyBytes = rsa.Encrypt(aes.Key);
            encMsg.SymmetricKey = FormatConverter.BytesToString64(encryptedSymmetricKeyBytes);

            // create digital signature of message text (using senders private key)
            string senderKeyPair = _storageService.GetUser().KeyPair;

            rsa = new RsaCipher(senderKeyPair);
            byte[] digitalSignatureBytes = rsa.CreateDigitalSignature(messageBytes);
            encMsg.DigitalSignature = FormatConverter.BytesToString64(digitalSignatureBytes);

            return(encMsg);
        }