public override byte[] ClientUdpPostDecrypt(byte[] plaindata, int datalength, out int outlength) { if (datalength <= 8) { outlength = 0; return(plaindata); } var md5 = CreateHMAC(user_key); var md5data = md5.ComputeHash(plaindata, 0, datalength - 1); if (md5data[0] != plaindata[datalength - 1]) { outlength = 0; return(plaindata); } md5 = CreateHMAC(Server.key); md5data = md5.ComputeHash(plaindata, datalength - 8, 7); var rand_len = UdpGetRandLen(random_server, md5data); outlength = datalength - rand_len - 8; encryptor = (StreamEncryptor)EncryptorFactory.GetEncryptor("chacha20", Convert.ToBase64String(user_key) + Convert.ToBase64String(md5data, 0, 16)); { var iv = new byte[8]; Array.Copy(Server.key, iv, 8); encryptor.Decrypt(iv, 8, plaindata, out _); } encryptor.Decrypt(plaindata, outlength, plaindata, out outlength); return(plaindata); }
/// <summary> /// Encrypts the committed file using the specified symmetric encryption key. /// </summary> /// <param name="key">The symmetric encryption key.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="key" /> is <c>null</c>.</exception> /// <exception cref="InvalidOperationException">Thrown if the file has not been committed to the cache.</exception> /// <exception cref="IOException">Thrown if there's a problem reading or writing file data.</exception> /// <exception cref="CryptographicException">Thrown if there's any encryption failure.</exception> /// <remarks> /// <note> /// This method may be called only on files that have been already been committed to the cache. /// </note> /// </remarks> public void Encrypt(SymmetricKey key) { if (key == null) { throw new ArgumentNullException("key"); } if (IsUploading) { throw new ArgumentNullException(string.Format("Cannot encrypt file [{0}] until it has been committed to the cache.", ID)); } if (!File.Exists(this.Path)) { throw new InvalidOperationException(string.Format("Cannot encrypt web transfer file with ID [{0}] because it does not exist.", ID)); } var encryptedTempPath = this.Path + ".encrypting"; using (var encryptor = new StreamEncryptor(key)) { encryptor.Encrypt(this.Path, encryptedTempPath); } File.Delete(this.Path); File.Move(encryptedTempPath, this.Path); }
public void StreamCryptography_FileEncrypt() { // Verify that we can encrypt one file to another and then decrypt it. var key = Crypto.GenerateSymmetricKey(CryptoAlgorithm.AES, 256); var inputPath = Path.GetTempFileName(); var encryptedPath = Path.GetTempFileName(); var decryptedPath = Path.GetTempFileName(); byte[] data; byte[] buffer; data = new byte[16 * 1024]; for (int i = 0; i < data.Length; i++) { data[i] = (byte)i; } try { using (var fs = new FileStream(inputPath, FileMode.Create, FileAccess.ReadWrite)) { fs.Write(data, 0, data.Length); } using (var encryptor = new StreamEncryptor(key)) { encryptor.Encrypt(inputPath, encryptedPath); } buffer = File.ReadAllBytes(encryptedPath); Assert.IsFalse(Helper.ArrayEquals(data, buffer)); using (var decryptor = new StreamDecryptor(key)) { decryptor.Decrypt(encryptedPath, decryptedPath); } buffer = File.ReadAllBytes(decryptedPath); Assert.IsTrue(Helper.ArrayEquals(data, buffer)); } finally { if (File.Exists(inputPath)) { File.Delete(inputPath); } if (File.Exists(encryptedPath)) { File.Delete(encryptedPath); } if (File.Exists(decryptedPath)) { File.Delete(decryptedPath); } } }
public void Test1() { string file = @"D:/test.txt"; string file2 = @"D:/test1.txt"; StreamReader outputStream = new StreamReader(file); StreamWriter inputStream = new StreamWriter(file2, false); StreamEncryptor encryptor = new StreamEncryptor(outputStream, inputStream); }
protected override void Disposing() { if (encryptor != null) { encryptor.Dispose(); encryptor = null; } }
public override byte[] ClientUdpPreEncrypt(byte[] plaindata, int datalength, out int outlength) { byte[] outdata = new byte[datalength + 1024]; if (user_key == null) { user_id = new byte[4]; int index_of_split = Server.param.IndexOf(':'); if (index_of_split > 0) { try { uint user = uint.Parse(Server.param.Substring(0, index_of_split)); user_key = System.Text.Encoding.UTF8.GetBytes(Server.param.Substring(index_of_split + 1)); BitConverter.GetBytes(user).CopyTo(user_id, 0); } catch (Exception ex) { Logging.Log(LogLevel.Warn, $"Faild to parse auth param, fallback to basic mode. {ex}"); } } if (user_key == null) { random.NextBytes(user_id); user_key = Server.key; } } byte[] auth_data = new byte[3]; random.NextBytes(auth_data); MbedTLS.HMAC md5 = CreateHMAC(Server.key); byte[] md5data = md5.ComputeHash(auth_data, 0, auth_data.Length); int rand_len = UdpGetRandLen(random_client, md5data); byte[] rand_data = new byte[rand_len]; random.NextBytes(rand_data); outlength = datalength + rand_len + 8; encryptor = (StreamEncryptor)EncryptorFactory.GetEncryptor("chacha20", Convert.ToBase64String(user_key) + Convert.ToBase64String(md5data, 0, 16)); { byte[] iv = new byte[8]; Array.Copy(Server.key, iv, 8); encryptor.SetIV(iv); } encryptor.Encrypt(plaindata, datalength, outdata, out datalength); rand_data.CopyTo(outdata, datalength); auth_data.CopyTo(outdata, outlength - 8); byte[] uid = new byte[4]; for (int i = 0; i < 4; ++i) { uid[i] = (byte)(user_id[i] ^ md5data[i]); } uid.CopyTo(outdata, outlength - 5); { md5 = CreateHMAC(user_key); md5data = md5.ComputeHash(outdata, 0, outlength - 1); Array.Copy(md5data, 0, outdata, outlength - 1, 1); } return(outdata); }
public void StreamCryptography_PartialStream() { // Verify that we can encrypt/decrypt a portion of a stream. var key = Crypto.GenerateSymmetricKey(CryptoAlgorithm.AES, 256); var data = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var input = new MemoryStream(); var encrypted = new MemoryStream(); var decrypted = new MemoryStream(); byte[] buffer; input.Write(data, 0, data.Length); // Verify encryption. using (var encryptor = new StreamEncryptor(key)) { encrypted.Write(new byte[] { 0 }, 0, 1); input.Position = 1; encryptor.Encrypt(input, encrypted, 8); encrypted.Write(new byte[] { 9 }, 0, 1); Assert.IsTrue(encrypted.Length > 2); encrypted.Position = 1; buffer = new byte[8]; encrypted.Read(buffer, 0, 8); Assert.IsFalse(Helper.ArrayEquals(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, buffer)); } // Verify decryption. using (var decryptor = new StreamDecryptor(key)) { buffer = new byte[] { 0 }; encrypted.Position = 0; encrypted.Read(buffer, 0, 1); decrypted.Write(buffer, 0, 1); decrypted.Position = 1; decryptor.Decrypt(encrypted, decrypted, (int)(encrypted.Length - 2)); buffer = new byte[] { 9 }; encrypted.Read(buffer, 0, 1); decrypted.Write(buffer, 0, 1); decrypted.Position = 0; buffer = new byte[(int)decrypted.Length]; decrypted.Read(buffer, 0, buffer.Length); Assert.IsTrue(Helper.ArrayEquals(data, buffer)); } }
private static StreamEncryptor CreateEncryptor(string algorithm, byte[] key, byte[] nonce) { switch (algorithm) { case "AES-SIV": return(StreamEncryptor.CreateAesCmacSivEncryptor(key, nonce)); case "AES-PMAC-SIV": return(StreamEncryptor.CreateAesPmacSivEncryptor(key, nonce)); default: throw new ArgumentException("Unknown algorithm."); } }
/// <summary> /// /// </summary> /// <param name="message"></param> public override void ProcessMessageBeforeDeserialize(System.Web.Services.Protocols.SoapMessage message) { StreamEncryptor compressor = StreamEncryptor.Create(EncryptionMode); try { compressor.ProcessStream(previousStream, currentStream, StreamProcessMode.Decrypt); } catch (Exception e) { throw new SoapException(e.Message, SoapException.ServerFaultCode, e); } }
public void Initialise() { _encryptionProvider = Aes.Create(); var ivMock = new Mock <IIV>(); ivMock.Setup(m => m.GenerateIV(It.IsAny <int>())).Returns(TestConstants.IvData); _iv = ivMock.Object; _key = Mock.Of <IKey>(); _streamEncryptor = new StreamEncryptor(new Key("password"), _iv, _encryptionProvider); _unencryptedFile = Mock.Of <IFile>(m => m.Read() == GetUnencryptedTestStream()); _encryptedFile = Mock.Of <IFile>(m => m.Read() == GetEncryptedTestStream()); }
public void TestLegacyDeriveKey() { string pass = "******"; byte[] passBytes = Encoding.UTF8.GetBytes(pass); byte[] key1 = new byte[32]; StreamEncryptor.LegacyDeriveKey(passBytes, key1, 32); byte[] key2 = { 0x7b, 0x14, 0xff, 0x93, 0xd6, 0x63, 0x27, 0xfa, 0xd4, 0xdc, 0x37, 0x86, 0x46, 0x86, 0x3f, 0xc4, 0x53, 0x04, 0xd0, 0xdb, 0xf3, 0x79, 0xbd, 0xb5, 0x54, 0x44, 0xf9, 0x91, 0x80, 0x50, 0x7e, 0xa2 }; string key1str = Convert.ToBase64String(key1); string key2str = Convert.ToBase64String(key2); Assert.IsTrue(key1str == key2str); }
private static void StreamExample() { // Messages to encrypt. var messages = new List <string> { "Now that the party is jumping", "With the bass kicked in, the fingers are pumpin'", "Quick to the point, to the point no faking", "I'm cooking MC's like a pound of bacon" }; // Create a 32-byte key. var key = Aead.GenerateKey256(); // Create a 8-byte STREAM nonce (required). var nonce = StreamEncryptor.GenerateNonce(); // Create STREAM encryptor and decryptor using the AES-CMAC-SIV // algorithm. They implement the IDisposable interface, // so it's best to create them inside using statement. using (var encryptor = StreamEncryptor.CreateAesCmacSivEncryptor(key, nonce)) using (var decryptor = StreamDecryptor.CreateAesCmacSivDecryptor(key, nonce)) { for (int i = 0; i < messages.Count; ++i) { // Calculate whether the message is the last message to encrypt. bool last = i == messages.Count - 1; // Convert the message to byte array first. var bytes = Encoding.UTF8.GetBytes(messages[i]); // Encrypt the message. var ciphertext = encryptor.Seal(bytes, null, last); // Decrypt the message. var message = decryptor.Open(ciphertext, null, last); // Convert the message back to string. var plaintext = Encoding.UTF8.GetString(bytes); // Print the decrypted message to the standard output. Console.WriteLine(plaintext); } } }
public void SecurityLoadAndSend(string file_name, NetworkStream networkStream, byte[] key, DIFFIE_HELMAN aes) { using (stream = new FileStream(file_name, FileMode.Open)) { long length = stream.Length; int read = 0; file_length = BitConverter.GetBytes(stream.Length); aes.Encrypt(this.file_length); //Шифруем длину данных networkStream.Write(file_length, 0, file_length.Length); while (length > 0) { read = stream.Read(buf, 0, buf.Length); this.buf = StreamEncryptor.Encrypt(this.buf, key); //Дешифруем данные ключём потокового шифратора aes.Encrypt(this.buf); //Шифруем данные для передачи по сети networkStream.Write(this.buf, 0, read); length -= read; } } }
public void StreamCryptography_EntireStream() { // Verify that we can encrypt an entire stream and the decrypt it. var key = Crypto.GenerateSymmetricKey(CryptoAlgorithm.AES, 256); var data = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var input = new MemoryStream(); var encrypted = new MemoryStream(); var decrypted = new MemoryStream(); byte[] buffer; input.Write(data, 0, data.Length); // Verify encryption. using (var encryptor = new StreamEncryptor(key)) { input.Position = 0; encryptor.Encrypt(input, encrypted); Assert.IsTrue(encrypted.Length > 0); encrypted.Position = 0; buffer = new byte[(int)encrypted.Length]; encrypted.Read(buffer, 0, buffer.Length); Assert.IsFalse(Helper.ArrayEquals(data, buffer)); } // Verify decryption. using (var decryptor = new StreamDecryptor(key)) { encrypted.Position = 0; decryptor.Decrypt(encrypted, decrypted); Assert.IsTrue(decrypted.Length > 0); decrypted.Position = 0; buffer = new byte[(int)decrypted.Length]; decrypted.Read(buffer, 0, buffer.Length); Assert.IsTrue(Helper.ArrayEquals(data, buffer)); } }
public void SecurityLoadAndSave(string file_name, NetworkStream networkStream, byte[] key, DIFFIE_HELMAN aes) { using (stream = new FileStream(file_name, FileMode.CreateNew)) { /*networkStream.Read(file_length, 0, file_length.Length); //Считываем длину данных в потоке long length = BitConverter.ToInt64(file_length, 0); //Переводим длину*/ byte[] file_data = null; FileProtocolReader.Read(ref file_data,networkStream); file_data = aes.Decript(file_data); this.buf = StreamEncryptor.Encrypt(file_data, key); //Шифруем потоковым шифратором stream.Write(buf, 0, buf.Length); //Записываем данные в файл /*int read = 0; while (networkStream.DataAvailable) { read = networkStream.Read(this.buf, 0, buf.Length); //Считываем данные из сетевого потока aes.Decript(this.buf); //Дешифруем данные из сети this.buf = StreamEncryptor.Encrypt(this.buf,key); //Шифруем потоковым шифратором stream.Write(buf, 0, read); //Записываем данные в файл length -= read; }*/ } }
public void PackAuthData(byte[] data, int datalength, byte[] outdata, out int outlength) { const int authhead_len = 4 + 8 + 4 + 16 + 4; var encrypt = new byte[24]; if (Server.data is AuthDataAesChain authData) { lock (authData) { if (authData.connectionID > 0xFF000000) { authData.clientID = null; } if (authData.clientID == null) { authData.clientID = new byte[4]; g_random.GetBytes(authData.clientID); authData.connectionID = (uint)BitConverter.ToInt32(authData.clientID, 0) % 0xFFFFFD; } authData.connectionID += 1; Array.Copy(authData.clientID, 0, encrypt, 4, 4); Array.Copy(BitConverter.GetBytes(authData.connectionID), 0, encrypt, 8, 4); } } outlength = authhead_len; var encrypt_data = new byte[32]; var key = new byte[Server.Iv.Length + Server.key.Length]; Server.Iv.CopyTo(key, 0); Server.key.CopyTo(key, Server.Iv.Length); var utc_time_second = (ulong)Math.Floor(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds); var utc_time = (uint)utc_time_second; Array.Copy(BitConverter.GetBytes(utc_time), 0, encrypt, 0, 4); encrypt[12] = (byte)Server.overhead; encrypt[13] = (byte)(Server.overhead >> 8); send_tcp_mss = 1024; //random.Next(1024) + 400; recv_tcp_mss = send_tcp_mss; encrypt[14] = (byte)send_tcp_mss; encrypt[15] = (byte)(send_tcp_mss >> 8); // first 12 bytes { var rnd = new byte[4]; random.NextBytes(rnd); rnd.CopyTo(outdata, 0); var md5 = CreateHMAC(key); var md5data = md5.ComputeHash(rnd, 0, rnd.Length); last_client_hash = md5data; Array.Copy(md5data, 0, outdata, rnd.Length, 8); } // uid & 16 bytes auth data { var uid = new byte[4]; var index_of_split = Server.param.IndexOf(':'); if (index_of_split > 0) { try { var user = uint.Parse(Server.param.Substring(0, index_of_split)); user_key = System.Text.Encoding.UTF8.GetBytes(Server.param.Substring(index_of_split + 1)); BitConverter.GetBytes(user).CopyTo(uid, 0); } catch (Exception ex) { Logging.Log(LogLevel.Warn, $"Faild to parse auth param, fallback to basic mode. {ex}"); } } if (user_key == null) { random.NextBytes(uid); user_key = Server.key; } for (var i = 0; i < 4; ++i) { uid[i] ^= last_client_hash[8 + i]; } var encrypt_key = user_key; var streamEncryptor = (StreamEncryptor)EncryptorFactory.GetEncryptor("aes-128-cbc", Convert.ToBase64String(encrypt_key) + SALT); streamEncryptor.SetIV(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }); streamEncryptor.Encrypt(encrypt, 16, encrypt_data, out _); streamEncryptor.Dispose(); Array.Copy(encrypt_data, 0, encrypt, 4, 16); uid.CopyTo(encrypt, 0); } // final HMAC { var md5 = CreateHMAC(user_key); var md5data = md5.ComputeHash(encrypt, 0, 20); last_server_hash = md5data; Array.Copy(md5data, 0, encrypt, 20, 4); } encrypt.CopyTo(outdata, 12); encryptor = (StreamEncryptor)EncryptorFactory.GetEncryptor("chacha20", Convert.ToBase64String(user_key) + Convert.ToBase64String(last_client_hash, 0, 16)); { var iv = new byte[8]; Array.Copy(last_client_hash, iv, 8); encryptor.SetIV(iv); } { encryptor.Decrypt(last_server_hash, 8, outdata, out _); } // combine first chunk { var pack_outdata = new byte[outdata.Length]; PackData(data, datalength, pack_outdata, out var pack_outlength); Array.Copy(pack_outdata, 0, outdata, outlength, pack_outlength); outlength += pack_outlength; } }
public void DeriveKey(byte[] password, byte[] key, int keylen) { StreamEncryptor.LegacyDeriveKey(password, key, keylen); }