Пример #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AesCbcHmacDecryptor"/> class.
        /// </summary>
        /// <param name="keyBytes"></param>
        /// <param name="encryptionAlgorithm"></param>
        /// <param name="decryptor"></param>
        public AesCbcHmacDecryptor(ReadOnlySpan <byte> keyBytes, EncryptionAlgorithm encryptionAlgorithm, AesDecryptor decryptor)
        {
            if (encryptionAlgorithm is null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.encryptionAlgorithm);
            }

            if (encryptionAlgorithm.Category != EncryptionType.AesHmac)
            {
                ThrowHelper.ThrowNotSupportedException_EncryptionAlgorithm(encryptionAlgorithm);
            }

            int keyLength = encryptionAlgorithm.RequiredKeySizeInBits >> 4;

            if (keyBytes.Length < keyLength)
            {
                ThrowHelper.ThrowArgumentOutOfRangeException_EncryptionKeyTooSmall(encryptionAlgorithm, encryptionAlgorithm.RequiredKeySizeInBits, keyBytes.Length >> 3);
            }

            _decryptor = decryptor;
            if (encryptionAlgorithm.SignatureAlgorithm is null)
            {
                ThrowHelper.ThrowNotSupportedException_SignatureAlgorithm(encryptionAlgorithm.SignatureAlgorithm);
            }

            _signer = new SymmetricSigner(keyBytes.Slice(0, keyLength), encryptionAlgorithm.SignatureAlgorithm);
        }
Пример #2
0
        public AesKeyUnwrapper(SymmetricJwk key, EncryptionAlgorithm encryptionAlgorithm, KeyManagementAlgorithm algorithm)
            : base(key, encryptionAlgorithm, algorithm)
        {
            if (algorithm.Category != AlgorithmCategory.Aes)
            {
                ThrowHelper.ThrowNotSupportedException_AlgorithmForKeyWrap(algorithm);
            }

#if !NETSTANDARD2_0 && !NET461 && !NETCOREAPP2_1
            if (algorithm == KeyManagementAlgorithm.Aes128KW)
            {
                _decryptor = new Aes128NiCbcDecryptor(key.K);
            }
            else if (algorithm == KeyManagementAlgorithm.Aes256KW)
            {
                _decryptor = new Aes256NiCbcDecryptor(key.K);
            }
            else if (algorithm == KeyManagementAlgorithm.Aes192KW)
            {
                _decryptor = new Aes192NiCbcDecryptor(key.K);
            }
            else
            {
                ThrowHelper.ThrowNotSupportedException_AlgorithmForKeyWrap(algorithm);
                _decryptor = new Aes128NiCbcDecryptor(default);
Пример #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AesCbcHmacDecryptor"/> class.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="encryptionAlgorithm"></param>
        public AesCbcHmacDecryptor(SymmetricJwk key, EncryptionAlgorithm encryptionAlgorithm)
        {
            if (key is null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
            }

            if (encryptionAlgorithm is null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.encryptionAlgorithm);
            }

            if (encryptionAlgorithm.Category != EncryptionType.AesHmac)
            {
                ThrowHelper.ThrowNotSupportedException_EncryptionAlgorithm(encryptionAlgorithm);
            }

            if (key.KeySizeInBits < encryptionAlgorithm.RequiredKeySizeInBits)
            {
                ThrowHelper.ThrowArgumentOutOfRangeException_EncryptionKeyTooSmall(key, encryptionAlgorithm, encryptionAlgorithm.RequiredKeySizeInBits, key.KeySizeInBits);
            }

            int keyLength = encryptionAlgorithm.RequiredKeySizeInBits >> 4;

            var keyBytes = key.K;
            var aesKey   = keyBytes.Slice(keyLength);

            _decryptor = new AesCbcDecryptor(aesKey, encryptionAlgorithm);
            if (encryptionAlgorithm.SignatureAlgorithm is null)
            {
                ThrowHelper.ThrowNotSupportedException_SignatureAlgorithm(encryptionAlgorithm.SignatureAlgorithm);
            }

            _signer = new SymmetricSigner(keyBytes.Slice(0, keyLength), encryptionAlgorithm.SignatureAlgorithm);
        }
Пример #4
0
        private bool AutoLogin()
        {
            var username = Request.QueryString["username"];
            var token    = Request.QueryString["token"];

            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(token))
            {
                var sharedSecret = ConfigurationManager.AppSettings["ILBFEDSharedSecret"];
                if (string.IsNullOrEmpty(sharedSecret))
                {
                    _lblError.Text = "Configuration invalid for automatic login. Please login manually.";
                    return(true);
                }

                token = HttpUtility.UrlDecode(token).Replace(' ', '+');
                var tokenParts = token.Split('|');
                var salt       = tokenParts[0];
                var ciphertext = tokenParts[1];

                var plaintext      = new AesDecryptor(sharedSecret).Decrypt(ciphertext, salt);
                var plaintextParts = plaintext.Split('|');
                var timestamp      = DateTime.Parse(plaintextParts[0]);
                var password       = plaintextParts[1];

                if (DateTime.Now > timestamp.AddSeconds(30))
                {
                    _lblError.Text = "Automatic login token has timed out. Please login manually.";
                    return(true);
                }

                DoLogin(username, password);
                return(true);
            }
            return(false);
        }
Пример #5
0
 public static byte[] Decode(byte[] arr, AesDecryptor aesDecryptor, ref int recvIdx)
 {
     //byte flag = arr[0];
     //bool ziped = ((flag & 0x80) == 0x80);
     //bool aesed = ((flag & 0x40) == 0x40);
     //bool crced = ((flag & 0x20) == 0x20);
     //int idx = flag & 0x1F;
     //if (recvIdx == idx || true)
     {
         //recvIdx++;
         //if (recvIdx > 0x1F)
         //{
         //    recvIdx = 0;
         //}
         //var bcrc = new byte[4];
         //Buffer.BlockCopy(arr, 1, bcrc, 0, 4);
         //CheckReverse(bcrc);
         //int crc32 = BitConverter.ToInt32(bcrc, 0);
         byte[] data;
         //var data = new byte[arr.Length - 1 - 4];
         //Buffer.BlockCopy(arr, 1 + 4, data, 0, data.Length);
         //int ncrc32 = 0;
         //if (crced)
         //{
         //    ncrc32 = Crc.Crc32(data);
         //}
         //if (ncrc32 == crc32 || true)
         {
             //if (aesed || true)
             {
                 data = arr;
                 data = aesDecryptor.Decrypt(data);
             }
             //if (ziped && false)
             //{
             //    data = ZLib.UnZip(data);
             //}
             if (data != null)
             {
                 return(data);
             }
             else
             {
                 throw new Exception("Recv Decode data null");
             }
         }
         //else
         //{
         //    throw new Exception("Recv error crc32 " + crc32 + "   ncrc32" + ncrc32);
         //}
     }
     //else
     //{
     //    throw new Exception("Recv error idx " + idx + "   lidx" + recvIdx);
     //}
 }
Пример #6
0
        internal static byte[] Decode(byte[] arr, AesDecryptor aesDecryptor, ref int recvIdx)
        {
            byte flag  = arr[0];
            bool ziped = ((flag & 0x80) == 0x80);
            bool aesed = ((flag & 0x40) == 0x40);
            bool crced = ((flag & 0x20) == 0x20);
            int  idx   = flag & 0x1F;

            if (recvIdx == idx)
            {
                recvIdx++;
                if (recvIdx > 0x1F)
                {
                    recvIdx = 0;
                }
                Byte[] bcrc = new Byte[4];
                Buffer.BlockCopy(arr, 1, bcrc, 0, 4);
                int    crc32 = BitConverter.ToInt32(bcrc, 0);
                Byte[] data  = new Byte[arr.Length - 1 - 4];
                Buffer.BlockCopy(arr, 1 + 4, data, 0, data.Length);
                int ncrc32 = 0;
                if (crced)
                {
                    ncrc32 = Crc.Crc32(data);
                }
                if (ncrc32 == crc32)
                {
                    if (aesed)
                    {
                        data = aesDecryptor.Decrypt(data);
                    }
                    if (ziped)
                    {
                        data = ZLib.UnZip(data);
                    }
                    if (data != null)
                    {
                        return(data);
                    }
                    else
                    {
                        TcpLogger.LogError("Recv Decode data null");
                    }
                }
                else
                {
                    TcpLogger.LogError("Recv error crc32 " + crc32 + "   ncrc32" + ncrc32);
                }
            }
            else
            {
                TcpLogger.LogError("Recv error idx " + idx + "   lidx" + recvIdx);
            }
            return(null);
        }
Пример #7
0
        public Connection(Socket sock, IMessageHandler handler, FunctionClose close, byte[] kiv)
        {
            IsRunning      = false;
            m_Initialized  = false;
            m_Socket       = sock;
            m_Handler      = handler;
            m_Close        = close;
            m_SendIdx      = 0;
            m_RecvIdx      = 0;
            m_AesDecryptor = new AesDecryptor(kiv, kiv);
            m_AesEncryptor = new AesEncryptor(kiv, kiv);
            var ep = (IPEndPoint)(sock.RemoteEndPoint);

            IP   = ep.Address.ToString();
            Port = ep.Port;
        }
Пример #8
0
        void HandleDataReceived(IAsyncResult ar)
        {
            var args = ar.AsyncState as NetClient.SocketArgs;

            try
            {
                int bytesRead = args.m_Socket.EndReceive(ar);
                if (bytesRead > 0)
                {
                    m_BufferReceivedSize += bytesRead;
                    if (m_BufferReceivedSize == m_Buffer.Length)
                    {
                        //解Aes Key IV
                        var decrypt = new AesDecryptor(m_KeyIV, m_KeyIV);
                        var bytes   = decrypt.Decrypt(m_Buffer);
                        if (!AesKeyIV.Check(bytes))
                        {
                            LogHelper.Error("Aes Key IV len error {0}", bytes.Length);
                            m_HandleClose?.Invoke(args);
                        }
                        else
                        {
                            m_HandleConnected?.Invoke(args, bytes);
                        }
                    }
                    else
                    {
                        args.m_Socket.BeginReceive(m_Buffer, m_BufferReceivedSize, m_Buffer.Length - m_BufferReceivedSize, SocketFlags.None, new AsyncCallback(HandleHeadReceived), args);
                    }
                }
                else
                {
                    LogHelper.Error(SocketError.NoData.ToString());
                    m_HandleClose?.Invoke(args);
                }
            }
            catch (Exception e)
            {
                LogHelper.Exception(e);
                m_HandleClose?.Invoke(args);
            }
        }
Пример #9
0
        private string Decrypt(string encData)
        {
            if (String.IsNullOrEmpty(encData))
            {
                return(String.Empty);
            }

            if (EncryptionVersion == 1)
            {
                var key       = EncryptionMode == EncryptionMode.Pattern ? EncryptionV1.EncryptionV1.GeneratePasswordHash(pattern, userId) : userId;
                var iv        = new SecureString().AppendChars("LCGoogleApps");
                var algorithm = EncryptionV1.EncryptionV1.CreateCryptoAlgorithm(key, iv);
                return(EncryptionV1.EncryptionV1.Decrypt(Base64.Decode(encData), algorithm));
            }
            else if (EncryptionVersion == 2)
            {
                var encBytes = Base64.Decode(encData);

                switch (EncryptionMode)
                {
                case EncryptionMode.Basic:
                    return(Encoding.UTF8.GetString(SymmetricEncryption.Decrypt(encBytes, userId)));

                case EncryptionMode.Pattern:
                    return(Encoding.UTF8.GetString(SymmetricEncryption.Decrypt(encBytes, pattern.Concat(userId))));

                case EncryptionMode.Password:
                    return(Encoding.UTF8.GetString(SymmetricEncryption.Decrypt(encBytes, password)));

                case EncryptionMode.PatternAndPassword:
                    return(Encoding.UTF8.GetString(SymmetricEncryption.Decrypt(encBytes, password.Concat(pattern))));

                default:
                    throw new NotImplementedException("Encryption mode not supported: " + EncryptionMode);
                }
            }
            else if (EncryptionVersion == 3)
            {
                var encBytes = Base64.Decode(encData);

                var aesDecryptor = new AesDecryptor(cryptoConfig);

                switch (EncryptionMode)
                {
                case EncryptionMode.Basic:
                    return(aesDecryptor.Decrypt(encBytes, userId));

                case EncryptionMode.Pattern:
                    return(aesDecryptor.Decrypt(encBytes, pattern.Concat(userId)));

                case EncryptionMode.Password:
                    return(aesDecryptor.Decrypt(encBytes, password));

                case EncryptionMode.PatternAndPassword:
                    return(aesDecryptor.Decrypt(encBytes, password.Concat(pattern)));

                default:
                    throw new NotImplementedException("Encryption mode not supported: " + EncryptionMode);
                }
            }
            else
            {
                throw new NotImplementedException("Encryption version not supported: " + EncryptionMode);
            }
        }
Пример #10
0
 void InitAesDecryptor()
 {
     m_AesDecryptor = new AesDecryptor(AesKey, AesIV);
 }