/// <summary> /// Packs to bytes. /// </summary> /// <param name="requestMessage">The request message.</param> /// <param name="rsaPublicKey">The RSA public key.</param> /// <param name="aesProvider">The aes provider.</param> /// <returns></returns> public static byte[] PackToBytes(this VirtualSecuredRequestRawMessage requestMessage, CryptoKey rsaPublicKey, 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}. try { rsaPublicKey.CheckNullObject(nameof(rsaPublicKey)); aesProvider.CheckNullObject(nameof(aesProvider)); requestMessage.CheckNullObject(nameof(requestMessage)); requestMessage.SymmetricPrimaryKey.CheckNullObject(nameof(requestMessage.SymmetricPrimaryKey)); requestMessage.Stamp.CheckNullObject(nameof(requestMessage.Stamp)); List <byte> result = new List <byte>(_packInitialCapacity) { // index1: version. Convert.ToByte(requestMessage.SchemaVersion) }; // index2: Stamp. result.AddRange(GetStampBytes(requestMessage.Stamp ?? DateTime.UtcNow)); // index3: Encrypted Security Key Length Indication. var encryptedSymmetricPrimaryKey = EncodingOrSecurityExtension.RsaEncrypt(requestMessage.SymmetricPrimaryKey, rsaPublicKey); var encryptedSymmetricSecondaryKey = (requestMessage.SymmetricSecondaryKey.ByteValue == null) ? null : EncodingOrSecurityExtension.RsaEncrypt(requestMessage.SymmetricSecondaryKey, rsaPublicKey); result.AddRange(BitConverter.GetBytes((UInt16)encryptedSymmetricPrimaryKey.Length)); result.AddRange(BitConverter.GetBytes((UInt16)encryptedSymmetricSecondaryKey.Length)); // index4: Encrypted Security Key result.AddRange(encryptedSymmetricPrimaryKey); if (encryptedSymmetricSecondaryKey.HasItem()) { result.AddRange(encryptedSymmetricSecondaryKey); } // index5: Encrypted content result.AddRange(aesProvider.EncryptAes(requestMessage.Data)); return(result.ToArray()); } catch (Exception ex) { throw ex.Handle(); } }