Beispiel #1
0
        public void SymmetricEncryptionEqualsTest()
        {
            string message = "aw3lrifos83fusoi3fjsofisjfo";

            byte[] messageBytes = Encoding.Unicode.GetBytes(message);

            var    asymmetricEncryption = new AsymmetricEncryption(_publicKey, _privateKey);
            string path       = Path.GetTempFileName();
            string outputPath = Path.GetTempFileName();

            asymmetricEncryption.EncryptSymmetrically(messageBytes, 256, 128, outputPath);

            byte[] encryptedBytes = File.ReadAllBytes(outputPath);

            int keyLen = BitConverter.ToInt32(encryptedBytes.Take(4).ToArray(), 0);

            byte[] key = encryptedBytes.Skip(4).Take(keyLen).ToArray();

            int ivLen = BitConverter.ToInt32(encryptedBytes.Skip(4 + key.Length).Take(4).ToArray(), 0);

            byte[] iv = encryptedBytes.Skip(4 + key.Length + 4).Take(ivLen).ToArray();

            key = asymmetricEncryption.DecryptToBytes(key);
            iv  = asymmetricEncryption.DecryptToBytes(iv);

            byte[] encryptedMessageBytes = encryptedBytes.Skip(4 + keyLen + 4 + ivLen).ToArray();

            SymmetricEncryption symmetricEncryption = new SymmetricEncryption(key, iv);
            string decryptedMessage = symmetricEncryption.DecryptToString(encryptedMessageBytes);

            Assert.AreEqual(message, decryptedMessage);
        }
        public async Task SymmetricEncryptionEqualsTest()
        {
            string message = "aw3lrifos83fusoi3fjsofisjfo";

            byte[] messageBytes = Encoding.UTF8.GetBytes(message);

            var          asymmetricEncryption = new AsymmetricEncryption(_publicKey, _privateKey);
            string       path            = Path.GetTempFileName();
            MemoryStream encryptedStream = new MemoryStream();
            await asymmetricEncryption.EnvelopeAsync(messageBytes, 256, 128, encryptedStream, CancellationToken.None);

            byte[] encryptedBytes = encryptedStream.ToArray();

            int keyLen = BitConverter.ToInt32(encryptedBytes.Take(4).ToArray(), 0);

            byte[] key = encryptedBytes.Skip(4).Take(keyLen).ToArray();

            int ivLen = BitConverter.ToInt32(encryptedBytes.Skip(4 + key.Length).Take(4).ToArray(), 0);

            byte[] iv = encryptedBytes.Skip(4 + key.Length + 4).Take(ivLen).ToArray();

            key = asymmetricEncryption.DecryptToBytes(key);
            iv  = asymmetricEncryption.DecryptToBytes(iv);

            byte[] encryptedMessageBytes = encryptedBytes.Skip(4 + keyLen + 4 + ivLen).ToArray();

            SymmetricEncryption symmetricEncryption = new SymmetricEncryption(key, iv);
            string decryptedMessage = symmetricEncryption.DecryptToString(encryptedMessageBytes, Encoding.UTF8);

            Assert.Equal(message, decryptedMessage);
        }