public void Test()
        {
            const string    aesKey          = "Mi9l/+7Zujhy12CE";
            const string    aesIV           = "Mi9l/+AB";
            SymmetricCrypto symmetricCrypto = new SymmetricCrypto(SymmetricCrypto.AlgorithmName.AesManaged, aesKey, aesIV);
            string          encryptedText   = symmetricCrypto.Encrypt("201807041500");
            string          clearText       = symmetricCrypto.Decrypt(encryptedText);

            Assert.AreEqual("201807041500", clearText);
        }
Exemplo n.º 2
0
        private void btnSymmetricDecrypt_Click(object sender, EventArgs e)
        {
            SymmetricCrypto crypto = CreateSymmetricCrypto();

            ByteArray key = new ByteArray(txtSymmetricKey.Text);

            byte[]    encrypted = Convert.FromBase64String(txtSymmetricEncrypted.Text);
            ByteArray data      = new ByteArray(encrypted);

            ByteArray decrypted = crypto.Decrypt(data, key);

            txtSymmetricDecrypted.Text = decrypted.Text;
        }
Exemplo n.º 3
0
    public static void CanEncryptDecryptAes()
    {
        var credential = new Credential(() => Key, SymmetricAlgorithm.Aes, 16);
        var crypto     = new SymmetricCrypto(new[] { credential });

        var plainText = "This is just some random text to encrypt/decrypt";
        var encrypted = crypto.Encrypt(plainText, null);
        var decrypted = crypto.Decrypt(encrypted, null);

        encrypted.Should().NotBe(plainText);
        decrypted.Should().NotBe(encrypted);
        decrypted.Should().Be(plainText);
    }
Exemplo n.º 4
0
        public void CanEncryptDecryptTripleDes()
        {
            var credential = new Credential(() => GetSequentialByteArray(24), SymmetricAlgorithm.TripleDES, 8);

            var crypto = new SymmetricCrypto(new[] { credential });

            var plainText = "This is just some random text to encrypt/decrypt";
            var encrypted = crypto.Encrypt(plainText, null);
            var decrypted = crypto.Decrypt(encrypted, null);

            encrypted.Should().NotBe(plainText);
            decrypted.Should().NotBe(encrypted);
            decrypted.Should().Be(plainText);
        }
        public void CanEncryptDecryptByRepoByEncryptionSettings()
        {
            var crypto = new SymmetricCrypto(new CryptoConfiguration
            {
                Credentials =
                {
                    new Credential(Convert.FromBase64String("1J9Og/OaZKWdfdwM6jWMpvlr3q3o7r20xxFDN7TEj6s="), SymmetricAlgorithm.Aes, 16)
                }
            }
                                             );

            var plainText = "This is just some random text to encrypt/decrypt";
            var encrypted = crypto.Encrypt(plainText, null);
            var decrypted = crypto.Decrypt(encrypted, null);

            encrypted.Should().NotBe(plainText);
            decrypted.Should().NotBe(encrypted);
            decrypted.Should().Be(plainText);
        }
Exemplo n.º 6
0
        public UserRegData DecryptRegData(string regText)
        {
            string[] parts = regText.Split(';');

            if (parts.Length < 5)
            {
                return(null);
            }

            // 0: Public key (XML)
            // 1: 數位簽章 (Base64)
            // 2: 對稱式加密金鑰 (Base64)
            // 3: 初始化向量 (Base64)
            // 4: 密文 (Base64)

            // 解密
            SymmetricCrypto crypto = new SymmetricCrypto(SymmetricCrypto.Provider.Rijndael, false);

            byte[] key = Convert.FromBase64String(parts[2]);
            crypto.IntializationVector = new ByteArray(Convert.FromBase64String(parts[3]));
            byte[] decryptedData = crypto.Decrypt(Convert.FromBase64String(parts[4]), key);

            // 驗證簽章
            ByteArray signature = new ByteArray(Convert.FromBase64String(parts[1]));

            CspParameters cspParams = new CspParameters();

            cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
            var rsa = new RSACryptoServiceProvider(cspParams);

            rsa.FromXmlString(parts[0]);
            bool valid = rsa.VerifyData(decryptedData, SHA1.Create(), signature.Bytes);

            if (!valid)
            {
                return(null);
            }

            string      decryptedText = Encoding.Default.GetString(decryptedData);
            UserRegData regData       = UserRegData.Parse(decryptedText);

            return(regData);
        }
        public void CanEncryptDecryptByCredentialRepositoryWithEncoding()
        {
            var credentialMock = new Mock <ICredential>();

            credentialMock.Setup(cm => cm.Algorithm).Returns(SymmetricAlgorithm.Aes);
            credentialMock.Setup(cm => cm.IVSize).Returns(16);
            credentialMock.Setup(cm => cm.GetKey()).Returns(GetSequentialByteArray(16));

            var credentialRepo = new CredentialRepository(new List <ICredential> {
                credentialMock.Object
            });

            var crypto = new SymmetricCrypto(credentialRepo, Encoding.ASCII);

            var plainText = "This is just some random text to encrypt/decrypt";
            var encrypted = crypto.Encrypt(plainText, null);
            var decrypted = crypto.Decrypt(encrypted, null);

            encrypted.Should().NotBe(plainText);
            decrypted.Should().NotBe(encrypted);
            decrypted.Should().Be(plainText);
        }
Exemplo n.º 8
0
 /// <summary>
 /// 标准的DES解密
 /// </summary>
 /// <param name="value">预解密值</param>
 /// <returns>已解密值</returns>
 public static string Decrypt(byte[] desKey, byte[] desIV, string value)
 {
     if (desKey.Length == 24) //3des
     {
         var crypto = new SymmetricCrypto(SymmetricMode.TripleDES, desKey, Encoding.ASCII);
         crypto.Mode    = CipherMode.ECB;
         crypto.Padding = PaddingMode.PKCS7;
         return(crypto.Decrypt(value));
     }
     else
     {
         using (DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider())
         {
             //从字符串转换为字节组
             byte[]       buffer = Convert.FromBase64String(value);
             MemoryStream ms     = new MemoryStream(buffer);
             CryptoStream cs     = new CryptoStream(ms, cryptoProvider.CreateDecryptor(desKey, desIV),
                                                    CryptoStreamMode.Read);
             StreamReader sr = new StreamReader(cs);
             return(sr.ReadToEnd());
         }
     }
 }
 /// <summary>
 /// Returns a <paramref name="storedItem"/> decryped into an item.
 /// </summary>
 protected TModel Decrypt(IStorableAsByteArray <TModel, TId> storedItem)
 {
     storedItem.ByteArray = _symmetricCrypto.Decrypt(storedItem.ByteArray);
     return(storedItem.Data);
 }
Exemplo n.º 10
0
        private protected void StartListeningOnSymetricProtocol_Thread()
        {
            _logger.Log(LogSeverity.System, $"{Thread.CurrentThread.Name} is ready!");

            // Initialzie new endpoint.
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(_configuration["CryptoConfig:server_ip"]), int.Parse(_configuration["CryptoConfig:server_port"]));

            // Define socket listener from the endpoint.
            Socket socketListener = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            // Bind the endpoint to the socket.
            socketListener.Bind(endPoint);

            // Listen on communication on the socket.
            socketListener.Listen(10);

            // Listen for connections..
            while (true)
            {
                // Handle incoming connection.
                Socket incomingSocketConnection = socketListener.Accept();

                // When the user connects set clientEndPointIpAddress to the ip as a string
                var clientEndPointIpAddress =
                    ((IPEndPoint)incomingSocketConnection.RemoteEndPoint).Address.ToString();

                // Run new thread on the current socket connection.
                Task.Run(async() =>
                {
                    bool isClientConnected = false;

                    // Check whether a client is connected to the endpoint socket.
                    if (incomingSocketConnection.Connected)
                    {
                        try
                        {
                            string xmlCryptoInfo = FormatCryptoInfo(new CryptoInfo("AES",
                                                                                   new[]
                            {
                                _configuration["CryptoConfig:Symmetrical:key"],
                                _configuration["CryptoConfig:Symmetrical:iv"]
                            })).GetAwaiter().GetResult();
                            // Send cryptoinfo
                            incomingSocketConnection.Send(Encoding.UTF8.GetBytes(xmlCryptoInfo));
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }


                        // Check ifthe client connected exists.
                        lock (_socketClientLocker)
                        {
                            if (SocketClients.Any(ip => ip.IpAddress == clientEndPointIpAddress))
                            {
                                // Get the client, and set their state to connected is true.
                                var getClient =
                                    SocketClients.FirstOrDefault(u => u.IpAddress == clientEndPointIpAddress);
                                if (getClient != null)
                                {
                                    getClient.ClientSocket.Disconnect(false);
                                    getClient.IsConnected  = true;
                                    getClient.ClientSocket = incomingSocketConnection;
                                }
                            }
                            // Add the client to the socket clients.
                            else
                            {
                                SocketClients.Add(new SocketClient(clientEndPointIpAddress, incomingSocketConnection,
                                                                   true));
                            }
                        }

                        // Log the client who has connected.
                        _logger.Log(LogSeverity.Info, $"Client Connected: {clientEndPointIpAddress}");
                        isClientConnected = true;

                        // Broadcast client states.
                        await BroadcastClientState(clientEndPointIpAddress);
                    }

                    while (true)
                    {
                        // Initialize a buffer to hold data.
                        byte[] dataBuffer = new byte[1024];

                        // Define an object to store the data in.
                        string readableData = null;

                        // Read incoming data from the connected client.
                        while (isClientConnected)
                        {
                            int bytesReceived = 0;

                            try
                            {
                                // Get the number of bytes received from the socket.
                                bytesReceived = incomingSocketConnection.Receive(dataBuffer);
                            }
                            catch (SocketException)
                            {
                                lock (_socketClientLocker)
                                {
                                    // Set the current socket user to disconnected.
                                    var getClient =
                                        SocketClients.FirstOrDefault(u => u.IpAddress == clientEndPointIpAddress);
                                    if (getClient != null)
                                    {
                                        getClient.IsConnected = false;
                                    }
                                }
                            }

                            // Check if the bytes received isn't zero.
                            if (bytesReceived != 0)
                            {
                                // Append the data with the length of bytes received on the specific index.
                                readableData += Encoding.UTF8.GetString(dataBuffer, 0, bytesReceived);

                                // Check if data contains end of file.
                                if (readableData.IndexOf("{END}") > -1)
                                {
                                    // Remove end of file data.
                                    readableData = readableData.Replace("{END}", string.Empty);
                                    break;
                                }
                            }
                            // Client is disconnected.
                            else
                            {
                                isClientConnected = false;
                                _logger.Log(LogSeverity.Info, $"Client Disconnected: {clientEndPointIpAddress}");
                                lock (_socketClientLocker)
                                {
                                    // Set the current socket user to disconnected.
                                    var getClient =
                                        SocketClients.FirstOrDefault(u => u.IpAddress == clientEndPointIpAddress);
                                    if (getClient != null)
                                    {
                                        getClient.IsConnected = false;
                                    }
                                }
                            }
                        }

                        // Check on data if client is connected.
                        if (isClientConnected)
                        {
                            try
                            {
                                // Store the message sent from the client, if fails, the format was incorrect.
                                var clientMessage = await FormatMessageFromXml(_symmetricCrypto.Decrypt(readableData).Result);

                                // Log the received message.
                                _logger.Log(LogSeverity.Info, $"Message Received: {clientMessage}");

                                try
                                {
                                    lock (_socketClientLocker)
                                    {
                                        // Check if any clients exists and is online, with the provided information sent from a client.
                                        if (SocketClients.Any(user =>
                                                              user.IpAddress == clientMessage.ReceiverIpAddress && user.IsConnected))
                                        {
                                            // Get the client to communicate with.
                                            var getClient = SocketClients.FirstOrDefault(user =>
                                                                                         user.IpAddress == clientMessage.ReceiverIpAddress);

                                            // Check that the client isn't null.
                                            if (getClient != null)
                                            {
                                                var xmlMessage       = FormatMessageToXml(clientMessage).GetAwaiter().GetResult();
                                                var encryptedMessage = _symmetricCrypto.Encrypt(xmlMessage).GetAwaiter().GetResult();

                                                // Deliver message to receiver client.
                                                getClient.ClientSocket.Send(Encoding.UTF8.GetBytes(encryptedMessage));

                                                // Notify client that their message has been delivered.
                                                incomingSocketConnection.Send(
                                                    Encoding.UTF8.GetBytes("Message has been delivered."));
                                            }
                                            // Notify the client, that their message couldn't be delivered.
                                            else
                                            {
                                                incomingSocketConnection.Send(
                                                    Encoding.UTF8.GetBytes("Message couldn't be delivered."));
                                            }
                                        }
                                        // Notify client with a message if the client isn't online or found.
                                        else
                                        {
                                            incomingSocketConnection.Send(
                                                Encoding.UTF8.GetBytes("Client is not online."));
                                        }
                                    }

                                    // Send data to client.
                                    //incomingSocketConnection.Send(Encoding.UTF8.GetBytes(readableData));
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e.Message);
                                }
                            }
                            catch (Exception)
                            {
                                incomingSocketConnection.Send(Encoding.UTF8.GetBytes("Message was in wrong format."));
                            }
                        }
                    }
                });
            }
        }