public void ReadFrom_InvalidInputs() { ExceptionAssert.Throws <ArgumentNullException>( () => CryptoStream.ReadFrom(null, new MockCryptoTransform(5))); ExceptionAssert.Throws <ArgumentException>( () => CryptoStream.ReadFrom(Stream.Null)); ExceptionAssert.Throws <ArgumentException>( () => CryptoStream.ReadFrom(Stream.Null, null)); }
public void ReadFrom() { var t1 = new MockCryptoTransform(6); var t2 = new MockCryptoTransform(9); var ms = new MemoryStream(Encoding.UTF8.GetBytes("abcdefghijkl")); using (var cryptoStream = CryptoStream.ReadFrom(ms, t1, t2)) { var buffer = new byte[100]; int bytesRead = cryptoStream.Read(buffer, 0, 100); Assert.AreEqual("--abcdef-g_hijkl_ZZ", Encoding.UTF8.GetString(buffer, 0, bytesRead)); } }
private static async Task PlayBobRoleAsync(ICryptographicKey ownSigningKey, ICryptographicKey othersSigningPublicKey, Stream channel, CancellationToken cancellationToken) { // Create ephemeral ECDH key pair, to prepare for the symmetric encryption key exchange. using (IECDiffieHellman? ecdhKeyPair = NetFxCrypto.ECDiffieHellman.Create()) { // Send the ephemeral ECDH public key to Alice. var ecdhPublicKey = ecdhKeyPair.PublicKey.ToByteArray(); await WriteAsync(channel, ecdhPublicKey, cancellationToken); // Authenticate to Alice that this is really Bob's ephemeral public key. byte[] ecdhPublicKeySignature = WinRTCrypto.CryptographicEngine.Sign(ownSigningKey, ecdhPublicKey); await WriteAsync(channel, ecdhPublicKeySignature, cancellationToken); // Read Alice's reply. It consists of her own ephemeral public key and signature. byte[] alicePublicDH = await ReadAsync(channel, cancellationToken); byte[] aliceSignedDH = await ReadAsync(channel, cancellationToken); // Authenticate Alice's public key. Assert.True(WinRTCrypto.CryptographicEngine.VerifySignature(othersSigningPublicKey, alicePublicDH, aliceSignedDH)); // Deserialize Alice's public key and derive the shared secret from it. IECDiffieHellmanPublicKey?aliceDHPK = NetFxCrypto.ECDiffieHellmanCngPublicKey.FromByteArray(alicePublicDH); byte[] encryptionKeyMaterial = ecdhKeyPair.DeriveKeyMaterial(aliceDHPK); ICryptographicKey?encryptionKey = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7) .CreateSymmetricKey(encryptionKeyMaterial); // Bob reads Alice's secret message using the shared secret that both parties derived, // but never transmitted. using (var aes = CryptoStream.ReadFrom(channel, WinRTCrypto.CryptographicEngine.CreateDecryptor(encryptionKey))) { byte[] plaintext = await ReadAsync(aes, cancellationToken); // Assert that the plaintext is as it was expected to be. Assert.Equal( Convert.ToBase64String(SecretMessage), Convert.ToBase64String(plaintext)); } channel.Dispose(); } }