Esempio n. 1
0
        /// <summary>
        /// 标准的DES加密
        /// </summary>
        /// <param name="value">预加密值</param>
        /// <returns>返回已加密值</returns>
        public static string Encrypt(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.Encrypt(value));
            }
            else
            {
                using (DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateEncryptor(desKey, desIV),
                                                           CryptoStreamMode.Write);
                        StreamWriter sw = new StreamWriter(cs);
                        sw.Write(value);
                        sw.Flush();
                        cs.FlushFinalBlock();
                        ms.Flush();

                        return(Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length));
                    }
                }
            }
        }
        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);
        }
        /// <summary>
        /// Encrypt an <paramref name="item"/> into a StorableAsByteArray.
        /// </summary>
        protected Core.Storage.Logic.StorableAsByteArray <TModel, TId> Encrypt(TModel item)
        {
            var storedItem = new Core.Storage.Logic.StorableAsByteArray <TModel, TId>
            {
                Data = item
            };

            storedItem.ByteArray = _symmetricCrypto.Encrypt(storedItem.ByteArray);
            return(storedItem);
        }
Esempio n. 4
0
        private void btnSymmetricEncrypt_Click(object sender, EventArgs e)
        {
            SymmetricCrypto crypto = CreateSymmetricCrypto();

            ByteArray key  = new ByteArray(txtSymmetricKey.Text);
            ByteArray data = new ByteArray(txtRawData.Text);

            ByteArray encrypted = crypto.Encrypt(data, key);

            txtSymmetricEncrypted.Text = encrypted.Base64String;
        }
Esempio n. 5
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);
    }
Esempio n. 6
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);
        }
Esempio n. 8
0
        /// <summary>
        /// 使用對稱式加密方法將輸入的資料加密。
        /// </summary>
        /// <param name="regData"></param>
        /// <param name="ipAddr"></param>
        /// <returns>以 Base64 編碼的字串,且分成三段,第一段為密鑰,第二段為初始化向量,第三段為密文。各段之間以分號 (;) 區隔。</returns>
        private string EncryptRegData(string regData, IPAddress ipAddr)
        {
            string ipStr = ipAddr.ToString();

            byte[] key  = ConvertHelper.StringToBytes(ipStr.Substring(0, 6));            // 取 IP 位址前六碼當作 key。
            byte[] data = ConvertHelper.StringToBytes(regData);

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

            byte[] encryptedData = crypto.Encrypt(data, key);

            StringBuilder sb = new StringBuilder();

            sb.Append(crypto.Key.Base64String);
            sb.Append(';');
            sb.Append(crypto.IntializationVector.Base64String);
            sb.Append(';');
            sb.Append(Convert.ToBase64String(encryptedData));

            return(sb.ToString());
        }
        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);
        }
Esempio 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."));
                            }
                        }
                    }
                });
            }
        }