public List <Message> GetEncryptedMessages(string token, string privatekey) { string privatekeyhash = SymmetricCryptoProvider.GetSecureHashForString(privatekey); WebClient client = new WebClient(); client.Headers.Add("token", token); client.Headers.Add("privatekeyhash", privatekeyhash); try { byte[] response = client.DownloadData(ServiceUrl); var responseText = Encoding.Default.GetString(response); var jss = new JavaScriptSerializer(); var resource = jss.Deserialize <List <Message> >(responseText); return(resource); } catch (WebException e) { HandleWebException(e); //throw; return(null); } }
public ActionResult GetFile(string fileId) { var key = FilePasswords.FirstOrDefault(p => p.Key == fileId && p.Value.Expires > DateTime.Now).Value; if (key == null) { Response.StatusCode = 500; return(Content("Temporary password has expired. Close this popup and re-enter your password.")); } Message message = requestRepository.GetMessageByMessageId(key.MessageId); string decryptedString = new SymmetricCryptoProvider().DecryptWithKey(message.MessageData, key.Passphrase); byte[] decryptedArray = Convert.FromBase64String(decryptedString); var zipStream = new MemoryStream(decryptedArray); var outputFileStream = new MemoryStream(); using (ZipFile zip = ZipFile.Read(zipStream)) { zip.First().Extract(outputFileStream); Response.AppendHeader("Content-Disposition", "attachment; filename=" + zip.First().FileName); } Response.ContentType = "application/octet-stream"; outputFileStream.Seek(0, SeekOrigin.Begin); return(new FileStreamResult(outputFileStream, "application/zip")); }
public void EncryptAndDecrypt_DifferenceInstances_ShouldBeDecryptedOk() { var plainText = "Arild"; var ecrypted = new SymmetricCryptoProvider().Encrypt(plainText); Encoding.UTF8.GetString(new SymmetricCryptoProvider().Decrypt(ecrypted)).Should().Be(plainText); }
private void btnDecrypt_Click(object sender, EventArgs e) { SymmetricCryptoProvider symmetricCrypt = new SymmetricCryptoProvider(); if (string.IsNullOrWhiteSpace(txtDecryptPassphrase.Text)) { MessageBox.Show("Cannot decrypt without a passphrase", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string plaintext = ""; try { plaintext = symmetricCrypt.DecryptWithKey(txtCypertext.Text, txtDecryptPassphrase.Text); } catch (CryptographicException) { MessageBox.Show("Unable to decrypt with provided passphrase", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } txtCypertext.Text = plaintext; tabControl1.SelectTab(0); }
public void EncryptAndDecryptWithAlgorithmName_DifferenceInstances_ShouldBeDecryptedWithOkOrFalse(string algorithmName, bool ok) { var plainText = "Arild"; Action action = () => { var ecrypted = new SymmetricCryptoProvider(getConfigValue).Encrypt(plainText); Encoding.UTF8.GetString(new SymmetricCryptoProvider(getConfigValue).Decrypt(ecrypted)).Should() .Be(plainText); }; if (ok) { action.Should().NotThrow(); } else { action.Should().Throw <Exception>(); } string getConfigValue(string key) { new Dictionary <string, string> { { "algorithm:name", algorithmName } }.TryGetValue(key, out var value); return(value); } }
public List <Message> GetDecryptedMessagesWithPassphrase(string keyToken, string passphrase) { Contract.Assert(!string.IsNullOrWhiteSpace(keyToken), "Token/Identifier is required to retrieve the messages!"); var db = new CryptAByteContext(); var request = db.Keys.Include("Messages").SingleOrDefault(key => key.KeyToken == keyToken); if (request == null) { throw new ArgumentOutOfRangeException("keyToken", "Request not found for this token."); } try { string privateKey = new SymmetricCryptoProvider().DecryptWithKey(request.PrivateKey, passphrase); return(GetDecryptedMessagesWithPrivateKey(keyToken, privateKey)); } catch (ArgumentNullException) { throw new ArgumentOutOfRangeException("passphrase", "error decrypting private key"); } catch (CryptographicException) { throw new ArgumentOutOfRangeException("passphrase", "error decrypting private key"); } }
/// <summary> /// Decrypts, decompresses and then deserializes an object from a byte array /// </summary> /// <typeparam name="T">The type of the serialized object</typeparam> /// <param name="encryptedBlob">The byte array containing the compressed and encrypted object</param> /// <returns></returns> public static T DecompressAndDecrypt <T>(byte[] encryptedBlob) { var crypto = new SymmetricCryptoProvider(SymmetricCryptoAlgorithm.AES); var decryptedBytes = crypto.DecryptBuffer(encryptedBlob); return(Decompress <T>(decryptedBytes)); }
public void EncryptAndDecrypt_SameInstance_ShouldBeDecryptedOk() { var plainText = "Arild"; var symmetricCryptoProvider = new SymmetricCryptoProvider(); var ecrypted = symmetricCryptoProvider.Encrypt(plainText); Encoding.UTF8.GetString(symmetricCryptoProvider.Decrypt(ecrypted)).Should().Be(plainText); }
public void SymmetricEncryption() { var secretMessage = "This is very secret"; var cipher = SymmetricCryptoProvider.SimpleEncryptWithPassword(secretMessage, "123456789123", Encoding.UTF8); var clear = SymmetricCryptoProvider.SimpleDecryptWithPassword(cipher, "123456789123", Encoding.UTF8); Assert.AreEqual(secretMessage, clear); }
/// <summary> /// Serializes, compresses and then encrypts the provided object into a byte array /// </summary> /// <param name="obj">The serializable object to process</param> /// <returns></returns> public static byte[] CompressAndEncrypt(object obj) { var compressedBytes = Compress(obj); var crypto = new SymmetricCryptoProvider(SymmetricCryptoAlgorithm.AES); return(crypto.EncryptBuffer(compressedBytes)); }
public void Encrypt_Decrypt_ReturnsOriginalValue() { var crypto = new SymmetricCryptoProvider(); var cryptoText = crypto.EncryptWithKey(secret, password); var original = crypto.DecryptWithKey(cryptoText, password); Assert.AreEqual(secret, original); }
public int StoreMessage(SelfDestructingMessage selfDestructingMessage, string passphrase, string attachmentName = null, byte[] attachmentData = null) { if (selfDestructingMessage == null) { throw new ArgumentOutOfRangeException("selfDestructingMessage required"); } selfDestructingMessage.Message = GzipCompression.Compress(selfDestructingMessage.Message); var crypto = new SymmetricCryptoProvider(); selfDestructingMessage.Message = crypto.EncryptWithKey(selfDestructingMessage.Message, passphrase); var db = new CryptAByteContext(); SelfDestructingMessageAttachment attachment = null; // save attachment, if it exists if (attachmentData != null && attachmentData.Length > 0) { MemoryStream streamOfOriginalFile = new MemoryStream(1024); using (ZipFile zip = new ZipFile()) { zip.AddEntry(attachmentName, attachmentData); // zip.AddEntry(self, fileData); zip.Save(streamOfOriginalFile); } byte[] zippedFile = RequestRepository.ReadFully(streamOfOriginalFile); string fileAsString = Convert.ToBase64String(zippedFile); attachment = new SelfDestructingMessageAttachment { Attachment = fileAsString }; attachment.Attachment = crypto.EncryptWithKey(fileAsString, passphrase); attachment.SentDate = DateTime.Now; //db.SelfDestructingMessageAttachments.Add(attachment); } db.SelfDestructingMessages.Add(selfDestructingMessage); db.SaveChanges(); if (attachment != null) { attachment.MessageId = selfDestructingMessage.MessageId; db.SelfDestructingMessageAttachments.Add(attachment); db.ChangeTracker.DetectChanges(); db.SaveChanges(); } return(selfDestructingMessage.MessageId); }
public void Encrypt_Decrypt_Hash_ReturnsOriginalValue() { var crypto = new SymmetricCryptoProvider(); string hashedPassword = SymmetricCryptoProvider.GetSecureHashForString(password); var cryptoText = crypto.EncryptWithKey(secret, hashedPassword); var original = crypto.DecryptWithKey(cryptoText, hashedPassword); Assert.AreEqual(secret, original); }
public void SymmetricEncryptionFile() { var path = @"C:\Test\test.txt"; var text = File.ReadAllText(path); SymmetricCryptoProvider.SimpleEncryptFileWithPassword(new FileInfo(path), "123456789123"); SymmetricCryptoProvider.SimpleDecryptFileWithPassword(new FileInfo(path), "123456789123"); var text2 = File.ReadAllText(path); Assert.AreEqual(text, text2); }
private static void StoreEncryptedFileInTemporaryMemory(Message message) { message.TemporaryDownloadId = SymmetricCryptoProvider.GenerateKeyPhrase(64); HomeController.FilePasswords.Add(message.TemporaryDownloadId, new TemporaryDownloadKey { Expires = DateTime.Now.AddSeconds(HomeController.PasswordExpiresInSeconds), MessageId = message.MessageId, Passphrase = message.EncryptionKey }); }
public void SymmetricEncryptionRaw() { byte[] key = new byte[16]; var rng = new RNGCryptoServiceProvider(); rng.GetBytes(key); var secretMessage = "This is very secret"; var cipher = SymmetricCryptoProvider.EncryptMessage(secretMessage, key, Encoding.UTF8); var clear = SymmetricCryptoProvider.DecryptMessage(cipher, key, Encoding.UTF8); Assert.AreEqual(secretMessage, clear); }
public SelfDestructingMessage GetMessage(int messageId, string passphrase) { var db = new CryptAByteContext(); SelfDestructingMessage message = db.SelfDestructingMessages.SingleOrDefault(m => m.MessageId == messageId); //.Include("SelfDestructingMessageAttachment") if (message == null) { throw new ArgumentOutOfRangeException("messageId", "Message not found. Was it already read?"); } var crypto = new SymmetricCryptoProvider(); try { message.Message = crypto.DecryptWithKey(message.Message, passphrase); var attachment = db.SelfDestructingMessageAttachments.FirstOrDefault(a => a.MessageId == messageId); if (attachment != null) { message.HasAttachment = true; // todo: get filename here } } catch (Exception) { throw new ArgumentOutOfRangeException("passphrase", "server error decrypting message"); } message.Message = GzipCompression.Decompress(message.Message); db.SelfDestructingMessages.Remove(message); db.SaveChanges(); message.SelfDestructingMessageAttachment = new SelfDestructingMessageAttachment { // AttachmentName = attachmentName }; return(message); }
public ActionResult Read(int messageId, string passphrase, string hash) { var model = new SelfDestructingMessageModel(); try { var message = selfDestructingMessageRepository.GetMessage(messageId, passphrase); string originalHash = SymmetricCryptoProvider.GetSecureHashForString(message.Message); if (hash != originalHash) { model.MessageText = "Error: hash of retrieved message does not match the original message hash." + Environment.NewLine + "The message may have been tampered with!"; model.InvalidMessageId = true; return(View("Read", model)); } // File Attachments if (message.HasAttachment) { Message attachment = new Message { EncryptionKey = passphrase, MessageId = message.MessageId }; StoreEncryptedFileInTemporaryMemory(attachment); model.HasAttachment = true; model.TemporaryDownloadId = attachment.TemporaryDownloadId; //model.AttachmentName = message.AttachmentName; } else { model.HasAttachment = false; } model.MessageText = message.Message; } catch (Exception ex) { model.InvalidMessageId = true; model.MessageText = ex.Message; } return(View("Read", model)); }
private void GenerateKeys(decimal keySize, decimal numberOfKeys) { StringBuilder keys = new StringBuilder(); for (int i = 1; i < numberOfKeys + 1; i++) { string key; if (chkCreatepronounceablepasswords.Checked) { key = PronounceablePasswordGenerator.Generate((int)keySize); } else { key = SymmetricCryptoProvider.GenerateKeyPhrase((int)keySize).TrimEnd(Convert.ToChar("=")); } int groupSize = (int)numGroupSize.Value; if (chkGroupIntoPairs.Checked && groupSize > 0) { string groupedKey = ""; for (int j = 0; j < key.Length; j++) { groupedKey += key[j]; if ((j + 1) % groupSize == 0) { groupedKey += "-"; } } groupedKey = groupedKey.TrimEnd('-'); keys.AppendLine(string.Format("{0}, {1}", i, groupedKey)); } else { keys.AppendLine(string.Format("{0}, {1}", i, key)); } } txtkeys.Text = keys.ToString(); }
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"); }
public SelfDestructingMessageAttachment GetAttachment(int messageId, string passphrase) { var db = new CryptAByteContext(); var crypto = new SymmetricCryptoProvider(); var attachment = db.SelfDestructingMessageAttachments.SingleOrDefault(m => m.MessageId == messageId); if (attachment != null) { attachment.Attachment = crypto.DecryptWithKey(attachment.Attachment, passphrase); db.SelfDestructingMessageAttachments.Remove(attachment); // todo: move decompression to this class } db.SaveChanges(); return(attachment); }
public static CryptoKey CreateRequestWithPassPhrase(string passphrase) { var key = AsymmetricCryptoProvider.GenerateKeys(); var request = new CryptoKey { RequestDate = DateTime.UtcNow, ReleaseDate = DateTime.Now, KeyToken = UniqueIdGenerator.GetUniqueId(), PublicKey = key.PublicKey, PrivateKey = new SymmetricCryptoProvider().EncryptWithKey(key.PrivateKey, passphrase), PrivateKeyHash = SymmetricCryptoProvider.GetSecureHashForString(key.PrivateKey), IsPrivateKeyEncrypted = true, IsPublicKeyOnly = false, Notifications = new EntityCollection<Notification>(), Messages = new EntityCollection<Message>(), }; return request; }
private void btnEncrypt_Click(object sender, EventArgs e) { SymmetricCryptoProvider symmetricCrypt = new SymmetricCryptoProvider(); string password = txtPassphrase.Text; if (string.IsNullOrWhiteSpace(password)) { password = PronounceablePasswordGenerator.Generate(10); MessageBox.Show( string.Format("Your random password is {0}. \r Please copy it now then click OK.", password), "Password generated", MessageBoxButtons.OK, MessageBoxIcon.Information); } string cypertext = symmetricCrypt.EncryptWithKey(txtClearText.Text, password); txtCypertext.Text = cypertext; tabControl1.SelectTab(1); }
private static void StoreEncryptedFileInTemporaryMemory(Message message) { message.TemporaryDownloadId = SymmetricCryptoProvider.GenerateKeyPhrase(64); FilePasswords.Add(message.TemporaryDownloadId, new TemporaryDownloadKey { Expires = DateTime.Now.AddSeconds(PasswordExpiresInSeconds), MessageId = message.MessageId, Passphrase = message.EncryptionKey }); // get filename byte[] decryptedArray = Convert.FromBase64String(message.MessageData); var zipStream = new MemoryStream(decryptedArray); using (ZipFile zip = ZipFile.Read(zipStream)) { message.MessageData = zip.First().FileName; } }
public void DeleteKeyWithPassphrase(string token, string passphrase) { var db = new CryptAByteContext(); var key = db.Keys.Include("Messages").SingleOrDefault(k => k.KeyToken == token); if (key == null) { throw new ArgumentOutOfRangeException("Key for this token not found. Was it already deleted?"); } var crypto = new SymmetricCryptoProvider(); try { var plaintext = crypto.DecryptWithKey(key.PrivateKey, passphrase); } catch (ArgumentException) { throw new ArgumentException("Failed to verify passphrase. A correct passphrase is required to verify the delete request."); } db.Keys.Remove(key); db.SaveChanges(); }
public ActionResult Send(SelfDestructingMessageModel message) { // verify email if (!Domain.Validation.IsValidEmail(message.Email)) { throw new ArgumentException("email", "invalid email format"); } string passphrase = PronounceablePasswordGenerator.Generate(32); passphrase = HttpUtility.UrlEncode(passphrase); int messageId = selfDestructingMessageRepository.StoreMessage(new SelfDestructingMessage() { Message = message.MessageText }, passphrase, message.AttachmentName, message.Attachment); string hash = SymmetricCryptoProvider.GetSecureHashForString(message.MessageText); const string notification = @" Hello, You have received a self-destructing message. This message will be decrypted and erased when you open the link below. You can read it at https://{0}:{1}/selfdestruct/read/?messageId={2}&passphrase={3}&hash={4} CryptAByte.com is not responsible for the contents of messages. For more information, please visit https://CryptAByte.com/SelfDestruct "; MailMessage mailMessage = new MailMessage { From = new MailAddress("*****@*****.**") }; mailMessage.To.Add(new MailAddress(message.Email)); mailMessage.Subject = "New self-destructing message @ CryptAByte"; if (Request == null) { string messageText = string.Format(notification, "cryptabyte.com", 443, messageId, passphrase, hash); Debug.WriteLine(messageText); mailMessage.Body = messageText; } else { mailMessage.Body = string.Format(notification, Request.Url.Host, Request.Url.Port, messageId, passphrase, hash);; } SmtpClient client = new SmtpClient(); client.Send(mailMessage); return(Content("Message sent")); }