/// <summary> /// Initializes a new instance of the <see cref="EncryptedMessage" /> class from a whole message bytes, which contain /// encrypted data. /// </summary> /// <param name="authKey"> /// Authorization Key a 2048-bit key shared by the client device and the server, created upon user /// registration directly on the client device be exchanging Diffie-Hellman keys, and never transmitted over a network. /// Each authorization key is user-specific. There is nothing that prevents a user from having several keys (that /// correspond to “permanent sessions” on different devices), and some of these may be locked forever in the event the /// device is lost. /// </param> /// <param name="messageBytes">Whole message bytes, which contain encrypted data.</param> /// <param name="sender">Sender of the message.</param> /// <param name="hashServices">Hash services.</param> /// <param name="encryptionServices">Encryption services.</param> public EncryptedMessage([NotNull] byte[] authKey, [NotNull] byte[] messageBytes, Sender sender, [NotNull] IHashServices hashServices, [NotNull] IEncryptionServices encryptionServices) { Argument.IsNotNull(() => authKey); Argument.IsNotNull(() => messageBytes); Argument.IsNotNull(() => hashServices); Argument.IsNotNull(() => encryptionServices); ulong authKeyId = ComputeAuthKeyId(authKey, hashServices); _messageBytes = messageBytes; _length = _messageBytes.Length; var encryptedData = new byte[_length - OuterHeaderLength]; using (var streamer = new TLStreamer(_messageBytes)) { // Reading header. _authKeyId = streamer.ReadUInt64(); if (_authKeyId != authKeyId) { throw new InvalidAuthKey(string.Format("Message encrypted with auth key with id={0}, but auth key provided for decryption with id={1}.", _authKeyId, authKeyId)); } _msgKey = streamer.ReadInt128(); // Reading encrypted data. streamer.Read(encryptedData, 0, encryptedData.Length); } // Decrypting. byte[] aesKey, aesIV; ComputeAesKeyAndIV(authKey, _msgKey, out aesKey, out aesIV, hashServices, sender); byte[] innerDataWithPadding = encryptionServices.Aes256IgeDecrypt(encryptedData, aesKey, aesIV); using (var streamer = new TLStreamer(innerDataWithPadding)) { _salt = streamer.ReadUInt64(); _sessionId = streamer.ReadUInt64(); _messageId = streamer.ReadUInt64(); _seqNumber = streamer.ReadUInt32(); _messageDataLength = streamer.ReadInt32(); _messageData = streamer.ReadBytes(_messageDataLength); } int innerDataLength = InnerHeaderLength + _messageDataLength; // When an encrypted message is received, it must be checked that // msg_key is in fact equal to the 128 lower-order bits // of the SHA1 hash of the previously encrypted portion. var msgKey = ComputeMsgKey(new ArraySegment <byte>(innerDataWithPadding, 0, innerDataLength), hashServices); if (_msgKey != msgKey) { throw new InvalidMessageException(string.Format("Expected message key to be {0}, but actual is {1}.", _msgKey, msgKey)); } }
public byte[] GetNonce(uint length) { return(_nonceStream.ReadBytes((int)length)); }