// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Management.Automation.Internal;
using System.Text;
using Xunit;

namespace PSTests.Parallel
{
    public static class CryptoUntilsTests
    {
        [Fact]
        public static void TestSessionKeyExchange()
        {
            using (var cryptoClient = PSRSACryptoServiceProvider.GetRSACryptoServiceProviderForClient())
            using (var cryptoServer = PSRSACryptoServiceProvider.GetRSACryptoServiceProviderForServer())
            {
                // generate, export, import public key
                cryptoClient.GenerateKeyPair();
                // public key generated by client
                string publicKey = cryptoClient.GetPublicKeyAsBase64EncodedString();
                cryptoServer.ImportPublicKeyFromBase64EncodedString(publicKey); // sent to and imported by server

                // generate, export, import session key 
                cryptoServer.GenerateSessionKey();   // server provides the session key?
                string sessionKey = cryptoServer.SafeExportSessionKey();
                cryptoClient.ImportSessionKeyFromBase64EncodedString(sessionKey);

                // encrypt
                byte[] plainText = Encoding.UTF8.GetBytes("here is a message");
                byte[] cipherText = cryptoClient.EncryptWithSessionKey(plainText);

                // decrypt
                byte[] decrypt = cryptoServer.DecryptWithSessionKey(cipherText);

                Assert.Equal(plainText, decrypt);
            }
        }
    }
}
