Compare commits

...

2 commits

Author SHA1 Message Date
Wizou 48d005b605 Encryption class public + Methods table
Some checks failed
Dev build / build (push) Has been cancelled
2025-10-10 20:27:42 +02:00
Wizou a5323eaa86 api doc 2025-10-06 18:34:25 +02:00
6 changed files with 923 additions and 344 deletions

View file

@ -32,6 +32,7 @@ public class MTProtoGenerator : IIncrementalGenerator
var nullables = LoadNullables(layer);
var namespaces = new Dictionary<string, Dictionary<string, string>>(); // namespace,class,methods
var tableTL = new StringBuilder();
var methodsTL = new StringBuilder();
var source = new StringBuilder();
source
.AppendLine("using System;")
@ -46,6 +47,9 @@ public class MTProtoGenerator : IIncrementalGenerator
tableTL
.AppendLine("\t\tpublic static readonly Dictionary<uint, Func<BinaryReader, IObject>> Table = new()")
.AppendLine("\t\t{");
methodsTL
.AppendLine("\t\tpublic static readonly Dictionary<uint, Func<BinaryReader, IObject>> Methods = new()")
.AppendLine("\t\t{");
foreach (var classDecl in unit.classes)
{
@ -86,8 +90,13 @@ public class MTProtoGenerator : IIncrementalGenerator
}
if (id == 0x3072CFA1) // GzipPacked
tableTL.AppendLine($"\t\t\t[0x{id:X8}] = reader => (IObject)reader.ReadTLGzipped(typeof(IObject)),");
else if (name != "Null" && (ns != "TL.Methods" || name == "Ping"))
tableTL.AppendLine($"\t\t\t[0x{id:X8}] = {(ns == "TL" ? "" : ns + '.')}{name}.ReadTL,");
else if (name != "Null")
{
if (ns == "TL.Methods")
methodsTL.AppendLine($"\t\t\t[0x{id:X8}] = {(ns == "TL" ? "" : ns + '.')}{name}{(symbol.IsGenericType ? "<IObject>" : "")}.ReadTL,");
if (ns != "TL.Methods" || name == "Ping")
tableTL.AppendLine($"\t\t\t[0x{id:X8}] = {(ns == "TL" ? "" : ns + '.')}{name}.ReadTL,");
}
var override_ = symbol.BaseType == object_ ? "" : "override ";
if (name == "Messages_AffectedMessages") override_ = "virtual ";
//if (symbol.Constructors[0].IsImplicitlyDeclared)
@ -213,7 +222,8 @@ public class MTProtoGenerator : IIncrementalGenerator
foreach (var nullable in nullables)
tableTL.AppendLine($"\t\t\t[0x{nullable.Value:X8}] = null,");
tableTL.AppendLine("\t\t};");
namespaces["TL"]["Layer"] = tableTL.ToString();
methodsTL.AppendLine("\t\t};");
namespaces["TL"]["Layer"] = tableTL.ToString() + methodsTL.ToString();
foreach (var namesp in namespaces)
{
source.Append("namespace ").AppendLine(namesp.Key).Append('{');

View file

@ -185,10 +185,6 @@ namespace WTelegram
return Console.ReadLine();
}
/// <summary>Load a specific Telegram server public key</summary>
/// <param name="pem">A string starting with <c>-----BEGIN RSA PUBLIC KEY-----</c></param>
public static void LoadPublicKey(string pem) => Encryption.LoadPublicKey(pem);
/// <summary>Builds a structure that is used to validate a 2FA password</summary>
/// <param name="accountPassword">Password validation configuration. You can obtain this via <c>Account_GetPassword</c> or through OnOther as part of the login process</param>
/// <param name="password">The password to validate</param>
@ -358,7 +354,7 @@ namespace WTelegram
if (await stream.FullReadAsync(data, 4, ct) != 4)
throw new WTException(ConnectionShutDown);
#if OBFUSCATION
_recvCtr.EncryptDecrypt(data, 4);
_recvCtr.EncryptDecrypt(data.AsSpan(0, 4));
#endif
int payloadLen = BinaryPrimitives.ReadInt32LittleEndian(data);
if (payloadLen <= 0)
@ -370,7 +366,7 @@ namespace WTelegram
if (await stream.FullReadAsync(data, payloadLen, ct) != payloadLen)
throw new WTException("Could not read frame data : Connection shut down");
#if OBFUSCATION
_recvCtr.EncryptDecrypt(data, payloadLen);
_recvCtr.EncryptDecrypt(data.AsSpan(0, payloadLen));
#endif
obj = ReadFrame(data, payloadLen);
}
@ -1526,7 +1522,7 @@ namespace WTelegram
int frameLength = (int)memStream.Length;
BinaryPrimitives.WriteInt32LittleEndian(buffer, frameLength - 4); // patch payload_len with correct value
#if OBFUSCATION
_sendCtr?.EncryptDecrypt(buffer, frameLength);
_sendCtr?.EncryptDecrypt(buffer.AsSpan(0, frameLength));
#endif
if (_networkStream != null)
await _networkStream.WriteAsync(buffer, 0, frameLength);

View file

@ -13,7 +13,7 @@ using static WTelegram.Compat;
namespace WTelegram
{
internal static class Encryption
public static class Encryption
{
private static readonly Dictionary<long, RSAPublicKey> PublicKeys = [];
internal static readonly RandomNumberGenerator RNG = RandomNumberGenerator.Create();
@ -237,6 +237,8 @@ namespace WTelegram
throw new WTException("g^a or g^b is not between 2^{2048-64} and dh_prime - 2^{2048-64}");
}
/// <summary>Load a specific Telegram server public key</summary>
/// <param name="pem">A string starting with <c>-----BEGIN RSA PUBLIC KEY-----</c></param>
public static void LoadPublicKey(string pem)
{
using var rsa = RSA.Create();
@ -319,7 +321,7 @@ j4WcDuXc2CTHgH8gFTNhp/Y8/SpDOhvn9QIDAQAB
}
#if OBFUSCATION
internal sealed class AesCtr(byte[] key, byte[] ivec) : IDisposable
public sealed class AesCtr(byte[] key, byte[] ivec) : IDisposable
{
readonly ICryptoTransform _encryptor = AesECB.CreateEncryptor(key, null);
readonly byte[] _ecount = new byte[16];
@ -327,9 +329,9 @@ j4WcDuXc2CTHgH8gFTNhp/Y8/SpDOhvn9QIDAQAB
public void Dispose() => _encryptor.Dispose();
public void EncryptDecrypt(byte[] buffer, int length)
public void EncryptDecrypt(Span<byte> buffer)
{
for (int i = 0; i < length; i++)
for (int i = 0; i < buffer.Length; i++)
{
if (_num == 0)
{
@ -373,7 +375,7 @@ j4WcDuXc2CTHgH8gFTNhp/Y8/SpDOhvn9QIDAQAB
var sendCtr = new AesCtr(sendKey, sendIV);
var recvCtr = new AesCtr(recvKey, recvIV);
var encrypted = (byte[])preamble.Clone();
sendCtr.EncryptDecrypt(encrypted, 64);
sendCtr.EncryptDecrypt(encrypted);
for (int i = 56; i < 64; i++)
preamble[i] = encrypted[i];
return (sendCtr, recvCtr, preamble);

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -3,7 +3,7 @@
namespace TL
{
#pragma warning disable IDE1006, CS1574
/// <summary>Object describes the contents of an encrypted message. <para>See <a href="https://corefork.telegram.org/type/DecryptedMessage"/></para></summary>
/// <summary>Object describes the contents of an encrypted message. <para>See <a href="https://corefork.telegram.org/type/DecryptedMessage"/></para> <para>Derived classes: <see cref="DecryptedMessage"/>, <see cref="DecryptedMessageService"/></para></summary>
public abstract partial class DecryptedMessageBase : IObject
{
/// <summary>Flags, see <a href="https://corefork.telegram.org/mtproto/TL-combinators#conditional-fields">TL conditional fields</a> (added in layer 45)</summary>
@ -24,11 +24,12 @@ namespace TL
public virtual long ReplyToRandom => default;
/// <summary>Random group ID, assigned by the author of message.<br/>Multiple encrypted messages with a photo attached and with the same group ID indicate an <a href="https://corefork.telegram.org/api/files#albums-grouped-media">album or grouped media</a> (parameter added in layer 45)</summary>
public virtual long Grouped => default;
/// <summary>Random bytes, removed in layer 17.</summary>
public virtual byte[] RandomBytes => default;
public virtual DecryptedMessageAction Action => default;
}
/// <summary>Object describes media contents of an encrypted message. <para>See <a href="https://corefork.telegram.org/type/DecryptedMessageMedia"/></para></summary>
/// <summary>Object describes media contents of an encrypted message. <para>See <a href="https://corefork.telegram.org/type/DecryptedMessageMedia"/></para> <para>Derived classes: <see cref="DecryptedMessageMediaPhoto"/>, <see cref="DecryptedMessageMediaVideo"/>, <see cref="DecryptedMessageMediaGeoPoint"/>, <see cref="DecryptedMessageMediaContact"/>, <see cref="DecryptedMessageMediaDocument"/>, <see cref="DecryptedMessageMediaAudio"/>, <see cref="DecryptedMessageMediaExternalDocument"/>, <see cref="DecryptedMessageMediaVenue"/>, <see cref="DecryptedMessageMediaWebPage"/></para></summary>
/// <remarks>a <see langword="null"/> value means <a href="https://corefork.telegram.org/constructor/decryptedMessageMediaEmpty">decryptedMessageMediaEmpty</a></remarks>
public abstract partial class DecryptedMessageMedia : IObject
{
@ -36,14 +37,17 @@ namespace TL
internal virtual (long size, byte[] key, byte[] iv) SizeKeyIV { get => default; set => throw new WTelegram.WTException("Incompatible DecryptedMessageMedia"); }
}
/// <summary>Object describes the action to which a service message is linked. <para>See <a href="https://corefork.telegram.org/type/DecryptedMessageAction"/></para></summary>
/// <summary>Object describes the action to which a service message is linked. <para>See <a href="https://corefork.telegram.org/type/DecryptedMessageAction"/></para> <para>Derived classes: <see cref="DecryptedMessageActionSetMessageTTL"/>, <see cref="DecryptedMessageActionReadMessages"/>, <see cref="DecryptedMessageActionDeleteMessages"/>, <see cref="DecryptedMessageActionScreenshotMessages"/>, <see cref="DecryptedMessageActionFlushHistory"/>, <see cref="DecryptedMessageActionResend"/>, <see cref="DecryptedMessageActionNotifyLayer"/>, <see cref="DecryptedMessageActionTyping"/>, <see cref="DecryptedMessageActionRequestKey"/>, <see cref="DecryptedMessageActionAcceptKey"/>, <see cref="DecryptedMessageActionAbortKey"/>, <see cref="DecryptedMessageActionCommitKey"/>, <see cref="DecryptedMessageActionNoop"/></para></summary>
public abstract partial class DecryptedMessageAction : IObject { }
/// <summary>Indicates the location of a photo, will be deprecated soon <para>See <a href="https://corefork.telegram.org/type/FileLocation"/></para></summary>
/// <summary>Indicates the location of a photo, will be deprecated soon <para>See <a href="https://corefork.telegram.org/type/FileLocation"/></para> <para>Derived classes: <see cref="FileLocationUnavailable"/>, <see cref="FileLocation"/></para></summary>
public abstract partial class FileLocationBase : IObject
{
/// <summary>Volume ID</summary>
public virtual long VolumeId => default;
/// <summary>Local ID</summary>
public virtual int LocalId => default;
/// <summary>Secret</summary>
public virtual long Secret => default;
}
@ -55,6 +59,7 @@ namespace TL
{
/// <summary>Random message ID, assigned by the author of message.<br/>Must be equal to the ID passed to sending method.</summary>
public long random_id;
/// <summary>Random bytes, removed in layer 17.</summary>
public byte[] random_bytes;
/// <summary>Message text</summary>
public string message;
@ -67,6 +72,7 @@ namespace TL
public override string Message => message;
/// <summary>Media content</summary>
public override DecryptedMessageMedia Media => media;
/// <summary>Random bytes, removed in layer 17.</summary>
public override byte[] RandomBytes => random_bytes;
}
/// <summary>Contents of an encrypted service message. <para>See <a href="https://corefork.telegram.org/constructor/decryptedMessageService"/></para></summary>
@ -75,12 +81,14 @@ namespace TL
{
/// <summary>Random message ID, assigned by the message author.<br/>Must be equal to the ID passed to the sending method.</summary>
public long random_id;
/// <summary>Random bytes, removed in Layer 17.</summary>
public byte[] random_bytes;
/// <summary>Action relevant to the service message</summary>
public DecryptedMessageAction action;
/// <summary>Random message ID, assigned by the message author.<br/>Must be equal to the ID passed to the sending method.</summary>
public override long RandomId => random_id;
/// <summary>Random bytes, removed in Layer 17.</summary>
public override byte[] RandomBytes => random_bytes;
/// <summary>Action relevant to the service message</summary>
public override DecryptedMessageAction Action => action;
@ -167,6 +175,7 @@ namespace TL
public int thumb_w;
/// <summary>Thumbnail height</summary>
public int thumb_h;
/// <summary>File name, moved to <c>attributes</c> in Layer 45.</summary>
public string file_name;
/// <summary>File MIME-type</summary>
public string mime_type;
@ -498,25 +507,38 @@ namespace TL
[TLDef(0x7C596B46)]
public sealed partial class FileLocationUnavailable : FileLocationBase
{
/// <summary>Volume ID</summary>
public long volume_id;
/// <summary>Local ID</summary>
public int local_id;
/// <summary>Secret</summary>
public long secret;
/// <summary>Volume ID</summary>
public override long VolumeId => volume_id;
/// <summary>Local ID</summary>
public override int LocalId => local_id;
/// <summary>Secret</summary>
public override long Secret => secret;
}
/// <summary>File location. <para>See <a href="https://corefork.telegram.org/constructor/fileLocation"/></para></summary>
[TLDef(0x53D69076)]
public sealed partial class FileLocation : FileLocationBase
{
/// <summary>DC ID</summary>
public int dc_id;
/// <summary>Volume ID</summary>
public long volume_id;
/// <summary>Local ID</summary>
public int local_id;
/// <summary>Secret</summary>
public long secret;
/// <summary>Volume ID</summary>
public override long VolumeId => volume_id;
/// <summary>Local ID</summary>
public override int LocalId => local_id;
/// <summary>Secret</summary>
public override long Secret => secret;
}
}
@ -775,7 +797,6 @@ namespace TL
{
/// <summary>Field <see cref="reply_to_random_id"/> has a value</summary>
has_reply_to_random_id = 0x8,
/// <summary>Whether this is a silent message (no notification triggered)</summary>
silent = 0x20,
/// <summary>Field <see cref="entities"/> has a value</summary>
has_entities = 0x80,