Exemplo n.º 1
0
        public bool Decrypt(EncryptedMessage encryptedMessage, int senderId, out string messageText)
        {
            if (encryptedMessage == null)
            {
                throw new ArgumentException("Encrypted message cannot be null");
            }

            if (encryptedMessage.Body == null || encryptedMessage.DigitalSignature == null ||
                encryptedMessage.SymmetricKey == null || encryptedMessage.Iv == null)
            {
                throw new ArgumentException("Not all encrypted message fields are initialized");
            }

            IContactModel senderContact = _storageService.GetContacts().FirstOrDefault(c => c.Id == senderId);

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

            string receiverKeyPair = _storageService.GetUser().KeyPair;
            string senderPublicKey = senderContact.PublicKey;

            try
            {
                // decrypt symmetric key with receivers private key
                RsaCipher rsa = new RsaCipher(receiverKeyPair);
                byte[]    encryptedSymmetricKeyBytes = FormatConverter.String64ToBytes(encryptedMessage.SymmetricKey);
                byte[]    decryptedSymmetricKeyBytes = rsa.Decrypt(encryptedSymmetricKeyBytes);

                // decrypt message text with jsut decrypted symmetric key
                byte[]    ivBytes = FormatConverter.String64ToBytes(encryptedMessage.Iv);
                AesCipher aes     = new AesCipher(decryptedSymmetricKeyBytes, ivBytes);
                byte[]    encryptedMessageBytes = FormatConverter.String64ToBytes(encryptedMessage.Body);
                byte[]    decryptedMessageBytes = aes.Decrypt(encryptedMessageBytes);

                // set message text out parameter
                messageText = FormatConverter.BytesToString(decryptedMessageBytes);

                // verify digital signature
                rsa = new RsaCipher(senderPublicKey);
                byte[] digitalSignatureBytes = FormatConverter.String64ToBytes(encryptedMessage.DigitalSignature);
                bool   signatureOk           = rsa.VerifyDigitalSignature(decryptedMessageBytes, digitalSignatureBytes);

                return(signatureOk);
            }
            catch (Exception ex)
            {
                messageText = null;
                return(false);
            }
        }