using System;
using System.Linq;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Text;

namespace ScanningRpcService
{
    public class DataProtectionApi
    {
        private static byte[] _entropy { get; } = CreateUniqueEntropy();
        private const DataProtectionScope _dataProtectionScope = System.Security.Cryptography.DataProtectionScope.LocalMachine;
        private readonly Encoding _defaultEncoding = Encoding.Unicode;



        public static byte[] CreateUniqueEntropy()
        {
            var macAddr =
            (
                from nic in NetworkInterface.GetAllNetworkInterfaces()
                where nic.OperationalStatus == OperationalStatus.Up
                select nic.GetPhysicalAddress().ToString()
            ).FirstOrDefault();
            string userValue = System.Security.Principal.WindowsIdentity.GetCurrent().User.Value;
            byte[] entropy = Encoding.ASCII.GetBytes(macAddr + userValue);

            return entropy;
        }
        public string Encrypt(string plainText)
        {

            if (String.IsNullOrEmpty(plainText))
            {
                return String.Empty;
            }

            var passwordBytes = _defaultEncoding.GetBytes(plainText);

            var cipherBytes = ProtectedData.Protect(passwordBytes, _entropy, _dataProtectionScope);

            return Convert.ToBase64String(cipherBytes);
        }

        public string Decrypt(string encrypted)
        {
            if (String.IsNullOrEmpty(encrypted))
            {
                return String.Empty;
            }

            var cipherBytes = Convert.FromBase64String(encrypted);

            var passwordBytes = ProtectedData.Unprotect(cipherBytes, _entropy, _dataProtectionScope);

            return _defaultEncoding.GetString(passwordBytes);
        }
    }
}

