public List <Message> GetDecryptedMessagesWithPrivateKey(string token, string privateKey) { var db = new CryptAByteContext(); var request = db.Keys.Include("Messages").SingleOrDefault(key => key.KeyToken == token); var crypto = new AsymmetricCryptoProvider(); if (!request.IsReleased) { throw new ArgumentOutOfRangeException("Request is not released"); } var plaintextMessages = new List <Message>(); if (request.Messages != null) { request.Messages.ToList().ForEach(retrievedMessage => { string messageDecryptionKey; var decryptedMessage = crypto.DecryptMessageWithKey(privateKey, retrievedMessage.MessageData, retrievedMessage.EncryptionKey, retrievedMessage.MessageHash, out messageDecryptionKey); retrievedMessage.MessageData = decryptedMessage; retrievedMessage.EncryptionKey = messageDecryptionKey; if (!retrievedMessage.IsFile) { retrievedMessage.MessageData = GzipCompression.Decompress(retrievedMessage.MessageData); } else { // this is a zip file } plaintextMessages.Add(retrievedMessage); }); if (request.DeleteMessagesAfterReading || request.DeleteKeyAfterReading) { if (request.DeleteMessagesAfterReading || request.DeleteKeyAfterReading) { request.Messages.ToList().ForEach(message => db.Messages.Remove(message)); } if (request.DeleteKeyAfterReading) { db.Keys.Remove(request); } db.SaveChanges(); } } return(plaintextMessages); }
public void Create_Message_Encrypt_Decrypt_Verify() { // Arrange: var repository = new RequestRepository(); var request = CryptoKey.CreateRequest(DateTime.Now); var keys = AsymmetricCryptoProvider.GenerateKeys(); var crypto = new AsymmetricCryptoProvider(); const string message = "secret message"; string encryptedPassword; string hash; string encryptedMessage = crypto.EncryptMessageWithKey(message, keys.PublicKey, out encryptedPassword, out hash); request.Messages.Add(new Message { MessageData = encryptedMessage, EncryptionKey = encryptedPassword, MessageHash = hash }); // Act: repository.AddRequest(request); var retrieved = repository.GetRequest(request.KeyToken); var retrievedMessage = retrieved.Messages.First(); string messageDecryptionKey; var decryptedMessage = crypto.DecryptMessageWithKey(keys.PrivateKey, retrievedMessage.MessageData, retrievedMessage.EncryptionKey, retrievedMessage.MessageHash, out messageDecryptionKey); // Assert: Assert.AreEqual(message, decryptedMessage); }
public void Message_Encrypt_Decrypt_ReturnsOriginalValue() { // Arrange var crypto = new AsymmetricCryptoProvider(); var key = AsymmetricCryptoProvider.GenerateKeys(); string hash; string encryptedPassword; // Act var encryptedMessage = crypto.EncryptMessageWithKey(secret, key.PublicKey, out encryptedPassword, out hash); string messageDecryptionKey; var decryptedSecret = crypto.DecryptMessageWithKey(key.PrivateKey, encryptedMessage, encryptedPassword, hash, out messageDecryptionKey); // Assert Assert.AreEqual(secret, decryptedSecret); Assert.AreEqual(SymmetricCryptoProvider.GetSecureHashForString(secret), hash, "hashes do not match"); }