/// <summary> /// Creates the encrypted Datagram. /// Client provides the encryption method to use as <typeparam name="T">SymmetricAlgorithm</typeparam>. /// </summary> /// <param name="key"></param> /// <param name="salt"></param> /// <returns></returns> public string CreateGramContent <T>(string key, string salt) where T : SymmetricAlgorithm, new() { DateTime Now = DateTime.Now.ToUniversalTime(); this._created = string.Format("{0:yyyy-MM-dd-TZ-HH:mm:ss.fff}", Now); this._messageLength = this._message.Length; StringBuilder SaltedMessage = new StringBuilder(this.Message); Random r = new Random((int)DateTime.Now.Ticks); int charCount = r.Next(3, 25); for (int charIndex = 0; charIndex < charCount; charIndex++) { SaltedMessage.Append((char)r.Next(32, 90)); } SecureGram work = new SecureGram(this); work.IsCompressed = this._messageLength >= 10000; if (work.IsCompressed) { MemoryStream messageCompressed = new MemoryStream(); using (var outGZipStream = new GZipStream(messageCompressed, CompressionLevel.Optimal)) { using (StreamWriter sw = new StreamWriter(outGZipStream)) { sw.Write(SaltedMessage.ToString()); sw.Close(); } } work.Message = Convert.ToBase64String(messageCompressed.ToArray()); } CipherUtility cipher = new CipherUtility(new T()); return (cipher.Encrypt( ObjectJsonSerializer <SecureGram> .CreateDocumentFormat(work), key, salt, Base64FormattingOptions.InsertLineBreaks)); }
/// <summary> /// Takes a string with the content of the encrypted message, and decrypts/decompresses/validates the content. /// Client provides the encryption method to use as <typeparam name="T">SymmetricAlgorithm</typeparam>. /// </summary> /// <param name="encryptedContent"></param> /// <param name="key"></param> /// <param name="salt"></param> public void LoadGramContent <T>(string encryptedContent, string key, string salt) where T : SymmetricAlgorithm, new() { CipherUtility cipher = new CipherUtility(new T()); this.Load( ObjectJsonSerializer <SecureGram> .CreateObjectFormat( cipher.Decrypt( encryptedContent, key, salt))); if (this._isCompressed) { MemoryStream messageCompressed = new MemoryStream(Convert.FromBase64String(this._message)); StringBuilder result = new StringBuilder(); using (var inGZipStream = new GZipStream(messageCompressed, CompressionMode.Decompress)) { const int size = 16384; byte[] buffer = new byte[size]; int count = 0; int TotalWritten = 0; while (TotalWritten < this._messageLength) { count = inGZipStream.Read(buffer, 0, size); if (TotalWritten + count > this._messageLength) { count = this._messageLength - TotalWritten; } for (int index = 0; index < count; index++) { result.Append((char)buffer[index]); } TotalWritten += count; } } this._message = result.ToString(); } }