Exemple #1
0
        /// <summary>
        /// Unpacks from bytes.
        /// </summary>
        /// <param name="requestBytes">The request bytes.</param>
        /// <param name="rsaProvider">The RSA provider.</param>
        /// <param name="aesProvider">The aes provider.</param>
        /// <returns></returns>
        public static VirtualSecuredRequestRawMessage UnpackRequestFromBytes(this byte[] requestBytes, RSACryptoServiceProvider rsaProvider, out RijndaelProvider aesProvider)
        {
            // Byte[] composition: [Schema Version]{1}[UTC Stamp]{4}[Encrypted Security Key Length Indication]{2+2}[Encrypted Security Key]{M+N}[Encrypted Body]{L}.
            aesProvider = null;

            try
            {
                rsaProvider.CheckNullObject(nameof(rsaProvider));
                requestBytes.CheckNullOrEmptyCollection(nameof(requestBytes));

                var result = new VirtualSecuredRequestRawMessage
                {
                    // Index1
                    SchemaVersion = Convert.ToInt32(requestBytes[0])
                };

                var currentIndex = 1;
                // Index2
                var stampBytes = requestBytes.Read(_stampIndicationByteLength, ref currentIndex);
                result.Stamp = GetUtcStampFromOffsetBytes(stampBytes);

                ValidateStamp(result.Stamp);

                // Index3
                var primaryKeyLengthBytes   = requestBytes.Read(_securityKeyIndicationByteLength, ref currentIndex);
                var primaryKeyLength        = BitConverter.ToUInt16(primaryKeyLengthBytes, 0);
                var secondaryKeyLengthBytes = requestBytes.Read(_securityKeyIndicationByteLength, ref currentIndex);
                var secondaryKeyLength      = BitConverter.ToUInt16(secondaryKeyLengthBytes, 0);

                // Index4
                var primaryKeyBytes = requestBytes.Read(primaryKeyLength, ref currentIndex);
                result.SymmetricPrimaryKey = rsaProvider.Decrypt(primaryKeyBytes, true);

                var secondaryKeyBytes = requestBytes.Read(secondaryKeyLength, ref currentIndex);
                result.SymmetricSecondaryKey = secondaryKeyBytes == null ? null : rsaProvider.Decrypt(secondaryKeyBytes, true);

                aesProvider = new AesKeys {
                    KeySize = dwKeySize, InitializationVector = result.SymmetricSecondaryKey, Key = result.SymmetricPrimaryKey
                }.CreateAesProvider();

                // Index5
                var dataBytes = requestBytes.SubArray(currentIndex);
                result.Data = aesProvider.DecryptAes(dataBytes);

                return(result);
            }
            catch (Exception ex)
            {
                throw ex.Handle();
            }
        }