mirror of
https://github.com/sochix/TLSharp.git
synced 2025-12-06 08:02:00 +01:00
TLSharp and Tests
This commit is contained in:
parent
9cf850e9b8
commit
3bb487a194
221
.gitignore
vendored
Normal file
221
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,221 @@
|
||||||
|
# Created by https://www.gitignore.io/api/isua,visualstudio
|
||||||
|
|
||||||
|
#!! ERROR: isua is undefined. Use list command to see defined gitignore types !!#
|
||||||
|
|
||||||
|
### VisualStudio ###
|
||||||
|
## Ignore Visual Studio temporary files, build results, and
|
||||||
|
## files generated by popular Visual Studio add-ons.
|
||||||
|
|
||||||
|
# User-specific files
|
||||||
|
*.suo
|
||||||
|
*.user
|
||||||
|
*.userosscache
|
||||||
|
*.sln.docstates
|
||||||
|
|
||||||
|
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||||
|
*.userprefs
|
||||||
|
|
||||||
|
# Build results
|
||||||
|
[Dd]ebug/
|
||||||
|
[Dd]ebugPublic/
|
||||||
|
[Rr]elease/
|
||||||
|
[Rr]eleases/
|
||||||
|
x64/
|
||||||
|
x86/
|
||||||
|
build/
|
||||||
|
bld/
|
||||||
|
[Bb]in/
|
||||||
|
[Oo]bj/
|
||||||
|
|
||||||
|
# Visual Studio 2015 cache/options directory
|
||||||
|
.vs/
|
||||||
|
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||||
|
#wwwroot/
|
||||||
|
|
||||||
|
# MSTest test Results
|
||||||
|
[Tt]est[Rr]esult*/
|
||||||
|
[Bb]uild[Ll]og.*
|
||||||
|
|
||||||
|
# NUNIT
|
||||||
|
*.VisualState.xml
|
||||||
|
TestResult.xml
|
||||||
|
|
||||||
|
# Build Results of an ATL Project
|
||||||
|
[Dd]ebugPS/
|
||||||
|
[Rr]eleasePS/
|
||||||
|
dlldata.c
|
||||||
|
|
||||||
|
# DNX
|
||||||
|
project.lock.json
|
||||||
|
artifacts/
|
||||||
|
|
||||||
|
*_i.c
|
||||||
|
*_p.c
|
||||||
|
*_i.h
|
||||||
|
*.ilk
|
||||||
|
*.meta
|
||||||
|
*.obj
|
||||||
|
*.pch
|
||||||
|
*.pdb
|
||||||
|
*.pgc
|
||||||
|
*.pgd
|
||||||
|
*.rsp
|
||||||
|
*.sbr
|
||||||
|
*.tlb
|
||||||
|
*.tli
|
||||||
|
*.tlh
|
||||||
|
*.tmp
|
||||||
|
*.tmp_proj
|
||||||
|
*.log
|
||||||
|
*.vspscc
|
||||||
|
*.vssscc
|
||||||
|
.builds
|
||||||
|
*.pidb
|
||||||
|
*.svclog
|
||||||
|
*.scc
|
||||||
|
|
||||||
|
# Chutzpah Test files
|
||||||
|
_Chutzpah*
|
||||||
|
|
||||||
|
# Visual C++ cache files
|
||||||
|
ipch/
|
||||||
|
*.aps
|
||||||
|
*.ncb
|
||||||
|
*.opensdf
|
||||||
|
*.sdf
|
||||||
|
*.cachefile
|
||||||
|
|
||||||
|
# Visual Studio profiler
|
||||||
|
*.psess
|
||||||
|
*.vsp
|
||||||
|
*.vspx
|
||||||
|
|
||||||
|
# TFS 2012 Local Workspace
|
||||||
|
$tf/
|
||||||
|
|
||||||
|
# Guidance Automation Toolkit
|
||||||
|
*.gpState
|
||||||
|
|
||||||
|
# ReSharper is a .NET coding add-in
|
||||||
|
_ReSharper*/
|
||||||
|
*.[Rr]e[Ss]harper
|
||||||
|
*.DotSettings.user
|
||||||
|
|
||||||
|
# JustCode is a .NET coding add-in
|
||||||
|
.JustCode
|
||||||
|
|
||||||
|
# TeamCity is a build add-in
|
||||||
|
_TeamCity*
|
||||||
|
|
||||||
|
# DotCover is a Code Coverage Tool
|
||||||
|
*.dotCover
|
||||||
|
|
||||||
|
# NCrunch
|
||||||
|
_NCrunch_*
|
||||||
|
.*crunch*.local.xml
|
||||||
|
nCrunchTemp_*
|
||||||
|
|
||||||
|
# MightyMoose
|
||||||
|
*.mm.*
|
||||||
|
AutoTest.Net/
|
||||||
|
|
||||||
|
# Web workbench (sass)
|
||||||
|
.sass-cache/
|
||||||
|
|
||||||
|
# Installshield output folder
|
||||||
|
[Ee]xpress/
|
||||||
|
|
||||||
|
# DocProject is a documentation generator add-in
|
||||||
|
DocProject/buildhelp/
|
||||||
|
DocProject/Help/*.HxT
|
||||||
|
DocProject/Help/*.HxC
|
||||||
|
DocProject/Help/*.hhc
|
||||||
|
DocProject/Help/*.hhk
|
||||||
|
DocProject/Help/*.hhp
|
||||||
|
DocProject/Help/Html2
|
||||||
|
DocProject/Help/html
|
||||||
|
|
||||||
|
# Click-Once directory
|
||||||
|
publish/
|
||||||
|
|
||||||
|
# Publish Web Output
|
||||||
|
*.[Pp]ublish.xml
|
||||||
|
*.azurePubxml
|
||||||
|
# TODO: Comment the next line if you want to checkin your web deploy settings
|
||||||
|
# but database connection strings (with potential passwords) will be unencrypted
|
||||||
|
*.pubxml
|
||||||
|
*.publishproj
|
||||||
|
|
||||||
|
# NuGet Packages
|
||||||
|
*.nupkg
|
||||||
|
# The packages folder can be ignored because of Package Restore
|
||||||
|
**/packages/*
|
||||||
|
# except build/, which is used as an MSBuild target.
|
||||||
|
!**/packages/build/
|
||||||
|
# Uncomment if necessary however generally it will be regenerated when needed
|
||||||
|
#!**/packages/repositories.config
|
||||||
|
|
||||||
|
# Windows Azure Build Output
|
||||||
|
csx/
|
||||||
|
*.build.csdef
|
||||||
|
|
||||||
|
# Windows Store app package directory
|
||||||
|
AppPackages/
|
||||||
|
|
||||||
|
# Visual Studio cache files
|
||||||
|
# files ending in .cache can be ignored
|
||||||
|
*.[Cc]ache
|
||||||
|
# but keep track of directories ending in .cache
|
||||||
|
!*.[Cc]ache/
|
||||||
|
|
||||||
|
# Others
|
||||||
|
ClientBin/
|
||||||
|
[Ss]tyle[Cc]op.*
|
||||||
|
~$*
|
||||||
|
*~
|
||||||
|
*.dbmdl
|
||||||
|
*.dbproj.schemaview
|
||||||
|
*.pfx
|
||||||
|
*.publishsettings
|
||||||
|
node_modules/
|
||||||
|
orleans.codegen.cs
|
||||||
|
|
||||||
|
# RIA/Silverlight projects
|
||||||
|
Generated_Code/
|
||||||
|
|
||||||
|
# Backup & report files from converting an old project file
|
||||||
|
# to a newer Visual Studio version. Backup files are not needed,
|
||||||
|
# because we have git ;-)
|
||||||
|
_UpgradeReport_Files/
|
||||||
|
Backup*/
|
||||||
|
UpgradeLog*.XML
|
||||||
|
UpgradeLog*.htm
|
||||||
|
|
||||||
|
# SQL Server files
|
||||||
|
*.mdf
|
||||||
|
*.ldf
|
||||||
|
|
||||||
|
# Business Intelligence projects
|
||||||
|
*.rdl.data
|
||||||
|
*.bim.layout
|
||||||
|
*.bim_*.settings
|
||||||
|
|
||||||
|
# Microsoft Fakes
|
||||||
|
FakesAssemblies/
|
||||||
|
|
||||||
|
# Node.js Tools for Visual Studio
|
||||||
|
.ntvs_analysis.dat
|
||||||
|
|
||||||
|
# Visual Studio 6 build log
|
||||||
|
*.plg
|
||||||
|
|
||||||
|
# Visual Studio 6 workspace options file
|
||||||
|
*.opt
|
||||||
|
|
||||||
|
# Visual Studio LightSwitch build output
|
||||||
|
**/*.HTMLClient/GeneratedArtifacts
|
||||||
|
**/*.DesktopClient/GeneratedArtifacts
|
||||||
|
**/*.DesktopClient/ModelManifest.xml
|
||||||
|
**/*.Server/GeneratedArtifacts
|
||||||
|
**/*.Server/ModelManifest.xml
|
||||||
|
_Pvt_Extensions
|
||||||
37
TLSharp.Core/Auth/Authenticator.cs
Normal file
37
TLSharp.Core/Auth/Authenticator.cs
Normal file
|
|
@ -0,0 +1,37 @@
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using TLSharp.Core.Network;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.Auth
|
||||||
|
{
|
||||||
|
public static class Authenticator
|
||||||
|
{
|
||||||
|
public static async Task<Step3_Response> DoAuthentication(TcpTransport transport)
|
||||||
|
{
|
||||||
|
var sender = new MtProtoPlainSender(transport);
|
||||||
|
var step1 = new Step1_PQRequest();
|
||||||
|
|
||||||
|
await sender.Send(step1.ToBytes());
|
||||||
|
var step1Response = step1.FromBytes(await sender.Recieve());
|
||||||
|
|
||||||
|
var step2 = new Step2_DHExchange();
|
||||||
|
await sender.Send(step2.ToBytes(
|
||||||
|
step1Response.Nonce,
|
||||||
|
step1Response.ServerNonce,
|
||||||
|
step1Response.Fingerprints,
|
||||||
|
step1Response.Pq));
|
||||||
|
|
||||||
|
var step2Response = step2.FromBytes(await sender.Recieve());
|
||||||
|
|
||||||
|
var step3 = new Step3_CompleteDHExchange();
|
||||||
|
await sender.Send(step3.ToBytes(
|
||||||
|
step2Response.Nonce,
|
||||||
|
step2Response.ServerNonce,
|
||||||
|
step2Response.NewNonce,
|
||||||
|
step2Response.EncryptedAnswer));
|
||||||
|
|
||||||
|
var step3Response = step3.FromBytes(await sender.Recieve());
|
||||||
|
|
||||||
|
return step3Response;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
96
TLSharp.Core/Auth/Step1_PQRequest.cs
Normal file
96
TLSharp.Core/Auth/Step1_PQRequest.cs
Normal file
|
|
@ -0,0 +1,96 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using TLSharp.Core.MTProto;
|
||||||
|
using TLSharp.Core.MTProto.Crypto;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.Auth
|
||||||
|
{
|
||||||
|
public class Step1_Response
|
||||||
|
{
|
||||||
|
public byte[] Nonce { get; set; }
|
||||||
|
public byte[] ServerNonce { get; set; }
|
||||||
|
public BigInteger Pq { get; set; }
|
||||||
|
public List<byte[]> Fingerprints { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class Step1_PQRequest
|
||||||
|
{
|
||||||
|
private byte[] nonce;
|
||||||
|
|
||||||
|
public Step1_PQRequest()
|
||||||
|
{
|
||||||
|
nonce = new byte[16];
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] ToBytes()
|
||||||
|
{
|
||||||
|
new Random().NextBytes(nonce);
|
||||||
|
const int constructorNumber = 0x60469778;
|
||||||
|
|
||||||
|
using (var memoryStream = new MemoryStream())
|
||||||
|
{
|
||||||
|
using (var binaryWriter = new BinaryWriter(memoryStream))
|
||||||
|
{
|
||||||
|
binaryWriter.Write(constructorNumber);
|
||||||
|
binaryWriter.Write(nonce);
|
||||||
|
|
||||||
|
return memoryStream.ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Step1_Response FromBytes(byte[] bytes)
|
||||||
|
{
|
||||||
|
var fingerprints = new List<byte[]>();
|
||||||
|
|
||||||
|
using (var memoryStream = new MemoryStream(bytes, false))
|
||||||
|
{
|
||||||
|
using (var binaryReader = new BinaryReader(memoryStream))
|
||||||
|
{
|
||||||
|
const int responseConstructorNumber = 0x05162463;
|
||||||
|
var responseCode = binaryReader.ReadInt32();
|
||||||
|
if (responseCode != responseConstructorNumber)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"invalid response code: {responseCode}");
|
||||||
|
}
|
||||||
|
|
||||||
|
var nonceFromServer = binaryReader.ReadBytes(16);
|
||||||
|
|
||||||
|
if (!nonceFromServer.SequenceEqual(nonce))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("invalid nonce from server");
|
||||||
|
}
|
||||||
|
|
||||||
|
var serverNonce = binaryReader.ReadBytes(16);
|
||||||
|
|
||||||
|
byte[] pqbytes = Serializers.Bytes.read(binaryReader);
|
||||||
|
var pq = new BigInteger(1, pqbytes);
|
||||||
|
|
||||||
|
var vectorId = binaryReader.ReadInt32();
|
||||||
|
const int vectorConstructorNumber = 0x1cb5c415;
|
||||||
|
if (vectorId != vectorConstructorNumber)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"Invalid vector constructor number {vectorId}");
|
||||||
|
}
|
||||||
|
|
||||||
|
var fingerprintCount = binaryReader.ReadInt32();
|
||||||
|
for (var i = 0; i < fingerprintCount; i++)
|
||||||
|
{
|
||||||
|
byte[] fingerprint = binaryReader.ReadBytes(8);
|
||||||
|
fingerprints.Add(fingerprint);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Step1_Response
|
||||||
|
{
|
||||||
|
Fingerprints = fingerprints,
|
||||||
|
Nonce = nonce,
|
||||||
|
Pq = pq,
|
||||||
|
ServerNonce = serverNonce
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
142
TLSharp.Core/Auth/Step2_DHExchange.cs
Normal file
142
TLSharp.Core/Auth/Step2_DHExchange.cs
Normal file
|
|
@ -0,0 +1,142 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using TLSharp.Core.MTProto;
|
||||||
|
using TLSharp.Core.MTProto.Crypto;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.Auth
|
||||||
|
{
|
||||||
|
public class Step2_Response
|
||||||
|
{
|
||||||
|
public byte[] Nonce { get; set; }
|
||||||
|
public byte[] ServerNonce { get; set; }
|
||||||
|
public byte[] NewNonce { get; set; }
|
||||||
|
public byte[] EncryptedAnswer { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class Step2_DHExchange
|
||||||
|
{
|
||||||
|
public byte[] newNonce;
|
||||||
|
|
||||||
|
public Step2_DHExchange()
|
||||||
|
{
|
||||||
|
newNonce = new byte[32];
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] ToBytes(byte[] nonce, byte[] serverNonce, List<byte[]> fingerprints, BigInteger pq)
|
||||||
|
{
|
||||||
|
new Random().NextBytes(newNonce);
|
||||||
|
|
||||||
|
var pqPair = Factorizator.Factorize(pq);
|
||||||
|
|
||||||
|
byte[] reqDhParamsBytes;
|
||||||
|
|
||||||
|
using (MemoryStream pqInnerData = new MemoryStream(255))
|
||||||
|
{
|
||||||
|
using (BinaryWriter pqInnerDataWriter = new BinaryWriter(pqInnerData))
|
||||||
|
{
|
||||||
|
pqInnerDataWriter.Write(0x83c95aec); // pq_inner_data
|
||||||
|
Serializers.Bytes.write(pqInnerDataWriter, pq.ToByteArrayUnsigned());
|
||||||
|
Serializers.Bytes.write(pqInnerDataWriter, pqPair.Min.ToByteArrayUnsigned());
|
||||||
|
Serializers.Bytes.write(pqInnerDataWriter, pqPair.Max.ToByteArrayUnsigned());
|
||||||
|
pqInnerDataWriter.Write(nonce);
|
||||||
|
pqInnerDataWriter.Write(serverNonce);
|
||||||
|
pqInnerDataWriter.Write(newNonce);
|
||||||
|
|
||||||
|
byte[] ciphertext = null;
|
||||||
|
byte[] targetFingerprint = null;
|
||||||
|
foreach (byte[] fingerprint in fingerprints)
|
||||||
|
{
|
||||||
|
ciphertext = RSA.Encrypt(BitConverter.ToString(fingerprint).Replace("-", string.Empty),
|
||||||
|
pqInnerData.GetBuffer(), 0, (int)pqInnerData.Position);
|
||||||
|
if (ciphertext != null)
|
||||||
|
{
|
||||||
|
targetFingerprint = fingerprint;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ciphertext == null)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
String.Format("not found valid key for fingerprints: {0}", String.Join(", ", fingerprints)));
|
||||||
|
}
|
||||||
|
|
||||||
|
using (MemoryStream reqDHParams = new MemoryStream(1024))
|
||||||
|
{
|
||||||
|
using (BinaryWriter reqDHParamsWriter = new BinaryWriter(reqDHParams))
|
||||||
|
{
|
||||||
|
reqDHParamsWriter.Write(0xd712e4be); // req_dh_params
|
||||||
|
reqDHParamsWriter.Write(nonce);
|
||||||
|
reqDHParamsWriter.Write(serverNonce);
|
||||||
|
Serializers.Bytes.write(reqDHParamsWriter, pqPair.Min.ToByteArrayUnsigned());
|
||||||
|
Serializers.Bytes.write(reqDHParamsWriter, pqPair.Max.ToByteArrayUnsigned());
|
||||||
|
reqDHParamsWriter.Write(targetFingerprint);
|
||||||
|
Serializers.Bytes.write(reqDHParamsWriter, ciphertext);
|
||||||
|
|
||||||
|
reqDhParamsBytes = reqDHParams.ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return reqDhParamsBytes;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Step2_Response FromBytes(byte[] response)
|
||||||
|
{
|
||||||
|
byte[] encryptedAnswer;
|
||||||
|
|
||||||
|
using (MemoryStream responseStream = new MemoryStream(response, false))
|
||||||
|
{
|
||||||
|
using (BinaryReader responseReader = new BinaryReader(responseStream))
|
||||||
|
{
|
||||||
|
uint responseCode = responseReader.ReadUInt32();
|
||||||
|
|
||||||
|
if (responseCode == 0x79cb045d)
|
||||||
|
{
|
||||||
|
// server_DH_params_fail
|
||||||
|
throw new InvalidOperationException("server_DH_params_fail: TODO");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (responseCode != 0xd0e8075c)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"invalid response code: {responseCode}");
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] nonceFromServer = responseReader.ReadBytes(16);
|
||||||
|
|
||||||
|
// TODO:!
|
||||||
|
/*
|
||||||
|
if (!nonceFromServer.SequenceEqual(nonce))
|
||||||
|
{
|
||||||
|
logger.debug("invalid nonce from server");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
byte[] serverNonceFromServer = responseReader.ReadBytes(16);
|
||||||
|
|
||||||
|
// TODO: !
|
||||||
|
/*
|
||||||
|
if (!serverNonceFromServer.SequenceEqual(serverNonce))
|
||||||
|
{
|
||||||
|
logger.error("invalid server nonce from server");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
encryptedAnswer = Serializers.Bytes.read(responseReader);
|
||||||
|
|
||||||
|
return new Step2_Response()
|
||||||
|
{
|
||||||
|
EncryptedAnswer = encryptedAnswer,
|
||||||
|
ServerNonce = serverNonceFromServer,
|
||||||
|
Nonce = nonceFromServer,
|
||||||
|
NewNonce = newNonce
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
209
TLSharp.Core/Auth/Step3_CompleteDHExchange.cs
Normal file
209
TLSharp.Core/Auth/Step3_CompleteDHExchange.cs
Normal file
|
|
@ -0,0 +1,209 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using TLSharp.Core.MTProto;
|
||||||
|
using TLSharp.Core.MTProto.Crypto;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.Auth
|
||||||
|
{
|
||||||
|
public class Step3_Response
|
||||||
|
{
|
||||||
|
public AuthKey AuthKey { get; set; }
|
||||||
|
public int TimeOffset { get; set; }
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public class Step3_CompleteDHExchange
|
||||||
|
{
|
||||||
|
private BigInteger _gab;
|
||||||
|
private byte[] newNonce;
|
||||||
|
private int timeOffset;
|
||||||
|
|
||||||
|
public byte[] ToBytes(byte[] nonce, byte[] serverNonce, byte[] newNonce, byte[] encryptedAnswer)
|
||||||
|
{
|
||||||
|
this.newNonce = newNonce;
|
||||||
|
AESKeyData key = AES.GenerateKeyDataFromNonces(serverNonce, newNonce);
|
||||||
|
byte[] plaintextAnswer = AES.DecryptAES(key, encryptedAnswer);
|
||||||
|
|
||||||
|
// logger.debug("plaintext answer: {0}", BitConverter.ToString(plaintextAnswer));
|
||||||
|
|
||||||
|
int g;
|
||||||
|
BigInteger dhPrime;
|
||||||
|
BigInteger ga;
|
||||||
|
|
||||||
|
using (MemoryStream dhInnerData = new MemoryStream(plaintextAnswer))
|
||||||
|
{
|
||||||
|
using (BinaryReader dhInnerDataReader = new BinaryReader(dhInnerData))
|
||||||
|
{
|
||||||
|
byte[] hashsum = dhInnerDataReader.ReadBytes(20);
|
||||||
|
uint code = dhInnerDataReader.ReadUInt32();
|
||||||
|
if (code != 0xb5890dba)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"invalid dh_inner_data code: {code}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// logger.debug("valid code");
|
||||||
|
|
||||||
|
byte[] nonceFromServer1 = dhInnerDataReader.ReadBytes(16);
|
||||||
|
if (!nonceFromServer1.SequenceEqual(nonce))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("invalid nonce in encrypted answer");
|
||||||
|
}
|
||||||
|
|
||||||
|
// logger.debug("valid nonce");
|
||||||
|
|
||||||
|
byte[] serverNonceFromServer1 = dhInnerDataReader.ReadBytes(16);
|
||||||
|
if (!serverNonceFromServer1.SequenceEqual(serverNonce))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("invalid server nonce in encrypted answer");
|
||||||
|
}
|
||||||
|
|
||||||
|
// logger.debug("valid server nonce");
|
||||||
|
|
||||||
|
g = dhInnerDataReader.ReadInt32();
|
||||||
|
dhPrime = new BigInteger(1, Serializers.Bytes.read(dhInnerDataReader));
|
||||||
|
ga = new BigInteger(1, Serializers.Bytes.read(dhInnerDataReader));
|
||||||
|
|
||||||
|
int serverTime = dhInnerDataReader.ReadInt32();
|
||||||
|
timeOffset = serverTime - (int)(Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds) / 1000);
|
||||||
|
|
||||||
|
// logger.debug("g: {0}, dhprime: {1}, ga: {2}", g, dhPrime, ga);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
BigInteger b = new BigInteger(2048, new Random());
|
||||||
|
BigInteger gb = BigInteger.ValueOf(g).ModPow(b, dhPrime);
|
||||||
|
_gab = ga.ModPow(b, dhPrime);
|
||||||
|
|
||||||
|
// logger.debug("gab: {0}", gab);
|
||||||
|
|
||||||
|
// prepare client dh inner data
|
||||||
|
byte[] clientDHInnerDataBytes;
|
||||||
|
using (MemoryStream clientDhInnerData = new MemoryStream())
|
||||||
|
{
|
||||||
|
using (BinaryWriter clientDhInnerDataWriter = new BinaryWriter(clientDhInnerData))
|
||||||
|
{
|
||||||
|
clientDhInnerDataWriter.Write(0x6643b654); // client_dh_inner_data
|
||||||
|
clientDhInnerDataWriter.Write(nonce);
|
||||||
|
clientDhInnerDataWriter.Write(serverNonce);
|
||||||
|
clientDhInnerDataWriter.Write((long)0); // TODO: retry_id
|
||||||
|
Serializers.Bytes.write(clientDhInnerDataWriter, gb.ToByteArrayUnsigned());
|
||||||
|
|
||||||
|
using (MemoryStream clientDhInnerDataWithHash = new MemoryStream())
|
||||||
|
{
|
||||||
|
using (BinaryWriter clientDhInnerDataWithHashWriter = new BinaryWriter(clientDhInnerDataWithHash))
|
||||||
|
{
|
||||||
|
using (SHA1 sha1 = new SHA1Managed())
|
||||||
|
{
|
||||||
|
clientDhInnerDataWithHashWriter.Write(sha1.ComputeHash(clientDhInnerData.GetBuffer(), 0, (int)clientDhInnerData.Position));
|
||||||
|
clientDhInnerDataWithHashWriter.Write(clientDhInnerData.GetBuffer(), 0, (int)clientDhInnerData.Position);
|
||||||
|
clientDHInnerDataBytes = clientDhInnerDataWithHash.ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// logger.debug("client dh inner data papared len {0}: {1}", clientDHInnerDataBytes.Length, BitConverter.ToString(clientDHInnerDataBytes).Replace("-", ""));
|
||||||
|
|
||||||
|
// encryption
|
||||||
|
byte[] clientDhInnerDataEncryptedBytes = AES.EncryptAES(key, clientDHInnerDataBytes);
|
||||||
|
|
||||||
|
// logger.debug("inner data encrypted {0}: {1}", clientDhInnerDataEncryptedBytes.Length, BitConverter.ToString(clientDhInnerDataEncryptedBytes).Replace("-", ""));
|
||||||
|
|
||||||
|
// prepare set_client_dh_params
|
||||||
|
byte[] setclientDhParamsBytes;
|
||||||
|
using (MemoryStream setClientDhParams = new MemoryStream())
|
||||||
|
{
|
||||||
|
using (BinaryWriter setClientDhParamsWriter = new BinaryWriter(setClientDhParams))
|
||||||
|
{
|
||||||
|
setClientDhParamsWriter.Write(0xf5045f1f);
|
||||||
|
setClientDhParamsWriter.Write(nonce);
|
||||||
|
setClientDhParamsWriter.Write(serverNonce);
|
||||||
|
Serializers.Bytes.write(setClientDhParamsWriter, clientDhInnerDataEncryptedBytes);
|
||||||
|
|
||||||
|
setclientDhParamsBytes = setClientDhParams.ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// logger.debug("set client dh params prepared: {0}", BitConverter.ToString(setclientDhParamsBytes));
|
||||||
|
|
||||||
|
return setclientDhParamsBytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Step3_Response FromBytes(byte[] response)
|
||||||
|
{
|
||||||
|
using (MemoryStream responseStream = new MemoryStream(response))
|
||||||
|
{
|
||||||
|
using (BinaryReader responseReader = new BinaryReader(responseStream))
|
||||||
|
{
|
||||||
|
uint code = responseReader.ReadUInt32();
|
||||||
|
if (code == 0x3bcbf734)
|
||||||
|
{ // dh_gen_ok
|
||||||
|
//logger.debug("dh_gen_ok");
|
||||||
|
|
||||||
|
|
||||||
|
byte[] nonceFromServer = responseReader.ReadBytes(16);
|
||||||
|
// TODO
|
||||||
|
/*
|
||||||
|
if (!nonceFromServer.SequenceEqual(nonce))
|
||||||
|
{
|
||||||
|
logger.error("invalid nonce");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
byte[] serverNonceFromServer = responseReader.ReadBytes(16);
|
||||||
|
|
||||||
|
// TODO:
|
||||||
|
|
||||||
|
/*
|
||||||
|
if (!serverNonceFromServer.SequenceEqual(serverNonce))
|
||||||
|
{
|
||||||
|
logger.error("invalid server nonce");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
byte[] newNonceHash1 = responseReader.ReadBytes(16);
|
||||||
|
//logger.debug("new nonce hash 1: {0}", BitConverter.ToString(newNonceHash1));
|
||||||
|
|
||||||
|
AuthKey authKey = new AuthKey(_gab);
|
||||||
|
|
||||||
|
byte[] newNonceHashCalculated = authKey.CalcNewNonceHash(newNonce, 1);
|
||||||
|
|
||||||
|
if (!newNonceHash1.SequenceEqual(newNonceHashCalculated))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("invalid new nonce hash");
|
||||||
|
}
|
||||||
|
|
||||||
|
//logger.info("generated new auth key: {0}", gab);
|
||||||
|
//logger.info("saving time offset: {0}", timeOffset);
|
||||||
|
//TelegramSession.Instance.TimeOffset = timeOffset;
|
||||||
|
|
||||||
|
return new Step3_Response()
|
||||||
|
{
|
||||||
|
AuthKey = authKey,
|
||||||
|
TimeOffset = timeOffset
|
||||||
|
};
|
||||||
|
}
|
||||||
|
else if (code == 0x46dc1fb9)
|
||||||
|
{ // dh_gen_retry
|
||||||
|
throw new NotImplementedException("dh_gen_retry");
|
||||||
|
|
||||||
|
}
|
||||||
|
else if (code == 0xa69dae02)
|
||||||
|
{
|
||||||
|
// dh_gen_fail
|
||||||
|
throw new NotImplementedException("dh_gen_fail");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"dh_gen unknown: {code}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
770
TLSharp.Core/MTProto/Crypto/AES.cs
Normal file
770
TLSharp.Core/MTProto/Crypto/AES.cs
Normal file
|
|
@ -0,0 +1,770 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.MTProto.Crypto
|
||||||
|
{
|
||||||
|
public class AESKeyData {
|
||||||
|
private readonly byte[] key;
|
||||||
|
private readonly byte[] iv;
|
||||||
|
|
||||||
|
public AESKeyData(byte[] key, byte[] iv) {
|
||||||
|
this.key = key;
|
||||||
|
this.iv = iv;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] Key {
|
||||||
|
get { return key; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] Iv {
|
||||||
|
get { return iv; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AES {
|
||||||
|
public static byte[] DecryptWithNonces(byte[] data, byte[] serverNonce, byte[] newNonce) {
|
||||||
|
using(SHA1 hash = new SHA1Managed()) {
|
||||||
|
var nonces = new byte[48];
|
||||||
|
|
||||||
|
newNonce.CopyTo(nonces, 0);
|
||||||
|
serverNonce.CopyTo(nonces, 32);
|
||||||
|
byte[] hash1 = hash.ComputeHash(nonces);
|
||||||
|
|
||||||
|
serverNonce.CopyTo(nonces, 0);
|
||||||
|
newNonce.CopyTo(nonces, 16);
|
||||||
|
byte[] hash2 = hash.ComputeHash(nonces);
|
||||||
|
|
||||||
|
nonces = new byte[64];
|
||||||
|
newNonce.CopyTo(nonces, 0);
|
||||||
|
newNonce.CopyTo(nonces, 32);
|
||||||
|
byte[] hash3 = hash.ComputeHash(nonces);
|
||||||
|
|
||||||
|
using(var keyBuffer = new MemoryStream(32))
|
||||||
|
using(var ivBuffer = new MemoryStream(32)) {
|
||||||
|
keyBuffer.Write(hash1, 0, hash1.Length);
|
||||||
|
keyBuffer.Write(hash2, 0, 12);
|
||||||
|
|
||||||
|
ivBuffer.Write(hash2, 12, 8);
|
||||||
|
ivBuffer.Write(hash3, 0, hash3.Length);
|
||||||
|
ivBuffer.Write(newNonce, 0, 4);
|
||||||
|
|
||||||
|
return DecryptIGE(data, keyBuffer.ToArray(), ivBuffer.ToArray());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static AESKeyData GenerateKeyDataFromNonces(byte[] serverNonce, byte[] newNonce) {
|
||||||
|
using (SHA1 hash = new SHA1Managed()) {
|
||||||
|
var nonces = new byte[48];
|
||||||
|
|
||||||
|
newNonce.CopyTo(nonces, 0);
|
||||||
|
serverNonce.CopyTo(nonces, 32);
|
||||||
|
byte[] hash1 = hash.ComputeHash(nonces);
|
||||||
|
|
||||||
|
serverNonce.CopyTo(nonces, 0);
|
||||||
|
newNonce.CopyTo(nonces, 16);
|
||||||
|
byte[] hash2 = hash.ComputeHash(nonces);
|
||||||
|
|
||||||
|
nonces = new byte[64];
|
||||||
|
newNonce.CopyTo(nonces, 0);
|
||||||
|
newNonce.CopyTo(nonces, 32);
|
||||||
|
byte[] hash3 = hash.ComputeHash(nonces);
|
||||||
|
|
||||||
|
using (var keyBuffer = new MemoryStream(32))
|
||||||
|
using (var ivBuffer = new MemoryStream(32)) {
|
||||||
|
keyBuffer.Write(hash1, 0, hash1.Length);
|
||||||
|
keyBuffer.Write(hash2, 0, 12);
|
||||||
|
|
||||||
|
ivBuffer.Write(hash2, 12, 8);
|
||||||
|
ivBuffer.Write(hash3, 0, hash3.Length);
|
||||||
|
ivBuffer.Write(newNonce, 0, 4);
|
||||||
|
|
||||||
|
return new AESKeyData(keyBuffer.ToArray(), ivBuffer.ToArray());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] DecryptAES(AESKeyData key, byte[] ciphertext) {
|
||||||
|
return DecryptIGE(ciphertext, key.Key, key.Iv);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] EncryptAES(AESKeyData key, byte[] plaintext) {
|
||||||
|
return EncryptIGE(plaintext, key.Key, key.Iv);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] DecryptIGE(byte[] ciphertext, byte[] key, byte[] iv) {
|
||||||
|
var iv1 = new byte[iv.Length/2];
|
||||||
|
var iv2 = new byte[iv.Length/2];
|
||||||
|
|
||||||
|
Array.Copy(iv, 0, iv1, 0, iv1.Length);
|
||||||
|
Array.Copy(iv, iv1.Length, iv2, 0, iv2.Length);
|
||||||
|
|
||||||
|
AesEngine aes = new AesEngine();
|
||||||
|
aes.Init(false, key);
|
||||||
|
|
||||||
|
byte[] plaintext = new byte[ciphertext.Length];
|
||||||
|
int blocksCount = ciphertext.Length/16;
|
||||||
|
|
||||||
|
byte[] ciphertextBlock = new byte[16];
|
||||||
|
byte[] plaintextBlock = new byte[16];
|
||||||
|
for(int blockIndex = 0; blockIndex < blocksCount; blockIndex++) {
|
||||||
|
for(int i = 0; i < 16; i++) {
|
||||||
|
ciphertextBlock[i] = (byte) (ciphertext[blockIndex*16 + i] ^ iv2[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
aes.ProcessBlock(ciphertextBlock, 0, plaintextBlock, 0);
|
||||||
|
|
||||||
|
for(int i = 0; i < 16; i++) {
|
||||||
|
plaintextBlock[i] ^= iv1[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
Array.Copy(ciphertext, blockIndex * 16, iv1, 0, 16);
|
||||||
|
Array.Copy(plaintextBlock, 0, iv2, 0, 16);
|
||||||
|
|
||||||
|
Array.Copy(plaintextBlock, 0, plaintext, blockIndex * 16, 16);
|
||||||
|
}
|
||||||
|
|
||||||
|
return plaintext;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] EncryptIGE(byte[] originPlaintext, byte[] key, byte[] iv) {
|
||||||
|
|
||||||
|
byte[] plaintext;
|
||||||
|
using (MemoryStream plaintextBuffer = new MemoryStream(originPlaintext.Length + 40)) {
|
||||||
|
//using(SHA1 hash = new SHA1Managed()) {
|
||||||
|
//byte[] hashsum = hash.ComputeHash(originPlaintext);
|
||||||
|
//plaintextBuffer.Write(hashsum, 0, hashsum.Length);
|
||||||
|
plaintextBuffer.Write(originPlaintext, 0, originPlaintext.Length);
|
||||||
|
while(plaintextBuffer.Position%16 != 0) {
|
||||||
|
plaintextBuffer.WriteByte(0); // TODO: random padding
|
||||||
|
}
|
||||||
|
plaintext = plaintextBuffer.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
var iv1 = new byte[iv.Length/2];
|
||||||
|
var iv2 = new byte[iv.Length/2];
|
||||||
|
|
||||||
|
Array.Copy(iv, 0, iv1, 0, iv1.Length);
|
||||||
|
Array.Copy(iv, iv1.Length, iv2, 0, iv2.Length);
|
||||||
|
|
||||||
|
AesEngine aes = new AesEngine();
|
||||||
|
aes.Init(true, key);
|
||||||
|
|
||||||
|
int blocksCount = plaintext.Length/16;
|
||||||
|
byte[] ciphertext = new byte[plaintext.Length];
|
||||||
|
|
||||||
|
byte[] ciphertextBlock = new byte[16];
|
||||||
|
byte[] plaintextBlock = new byte[16];
|
||||||
|
for(int blockIndex = 0; blockIndex < blocksCount; blockIndex++) {
|
||||||
|
Array.Copy(plaintext, 16*blockIndex, plaintextBlock, 0, 16);
|
||||||
|
|
||||||
|
//logger.info("plaintext block: {0} xor {1}", BitConverter.ToString(plaintextBlock).Replace("-", ""), BitConverter.ToString(iv1).Replace("-", ""));
|
||||||
|
|
||||||
|
for(int i = 0; i < 16; i++) {
|
||||||
|
plaintextBlock[i] ^= iv1[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
//logger.info("xored plaintext: {0}", BitConverter.ToString(plaintextBlock).Replace("-", ""));
|
||||||
|
|
||||||
|
aes.ProcessBlock(plaintextBlock, 0, ciphertextBlock, 0);
|
||||||
|
|
||||||
|
//logger.info("encrypted plaintext: {0} xor {1}", BitConverter.ToString(ciphertextBlock).Replace("-", ""), BitConverter.ToString(iv2).Replace("-", ""));
|
||||||
|
|
||||||
|
for(int i = 0; i < 16; i++) {
|
||||||
|
ciphertextBlock[i] ^= iv2[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
//logger.info("xored ciphertext: {0}", BitConverter.ToString(ciphertextBlock).Replace("-", ""));
|
||||||
|
|
||||||
|
Array.Copy(ciphertextBlock, 0, iv1, 0, 16);
|
||||||
|
Array.Copy(plaintext, 16*blockIndex, iv2, 0, 16);
|
||||||
|
|
||||||
|
Array.Copy(ciphertextBlock, 0, ciphertext, blockIndex * 16, 16);
|
||||||
|
}
|
||||||
|
|
||||||
|
return ciphertext;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] XOR(byte[] buffer1, byte[] buffer2) {
|
||||||
|
var result = new byte[buffer1.Length];
|
||||||
|
for(int i = 0; i < buffer1.Length; i++)
|
||||||
|
result[i] = (byte) (buffer1[i] ^ buffer2[i]);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// AES engine implementation
|
||||||
|
|
||||||
|
public class AesEngine {
|
||||||
|
// The S box
|
||||||
|
private const uint m1 = 0x80808080;
|
||||||
|
private const uint m2 = 0x7f7f7f7f;
|
||||||
|
private const uint m3 = 0x0000001b;
|
||||||
|
private const int BLOCK_SIZE = 16;
|
||||||
|
|
||||||
|
private static readonly byte[] S = {
|
||||||
|
99, 124, 119, 123, 242, 107, 111, 197,
|
||||||
|
48, 1, 103, 43, 254, 215, 171, 118,
|
||||||
|
202, 130, 201, 125, 250, 89, 71, 240,
|
||||||
|
173, 212, 162, 175, 156, 164, 114, 192,
|
||||||
|
183, 253, 147, 38, 54, 63, 247, 204,
|
||||||
|
52, 165, 229, 241, 113, 216, 49, 21,
|
||||||
|
4, 199, 35, 195, 24, 150, 5, 154,
|
||||||
|
7, 18, 128, 226, 235, 39, 178, 117,
|
||||||
|
9, 131, 44, 26, 27, 110, 90, 160,
|
||||||
|
82, 59, 214, 179, 41, 227, 47, 132,
|
||||||
|
83, 209, 0, 237, 32, 252, 177, 91,
|
||||||
|
106, 203, 190, 57, 74, 76, 88, 207,
|
||||||
|
208, 239, 170, 251, 67, 77, 51, 133,
|
||||||
|
69, 249, 2, 127, 80, 60, 159, 168,
|
||||||
|
81, 163, 64, 143, 146, 157, 56, 245,
|
||||||
|
188, 182, 218, 33, 16, 255, 243, 210,
|
||||||
|
205, 12, 19, 236, 95, 151, 68, 23,
|
||||||
|
196, 167, 126, 61, 100, 93, 25, 115,
|
||||||
|
96, 129, 79, 220, 34, 42, 144, 136,
|
||||||
|
70, 238, 184, 20, 222, 94, 11, 219,
|
||||||
|
224, 50, 58, 10, 73, 6, 36, 92,
|
||||||
|
194, 211, 172, 98, 145, 149, 228, 121,
|
||||||
|
231, 200, 55, 109, 141, 213, 78, 169,
|
||||||
|
108, 86, 244, 234, 101, 122, 174, 8,
|
||||||
|
186, 120, 37, 46, 28, 166, 180, 198,
|
||||||
|
232, 221, 116, 31, 75, 189, 139, 138,
|
||||||
|
112, 62, 181, 102, 72, 3, 246, 14,
|
||||||
|
97, 53, 87, 185, 134, 193, 29, 158,
|
||||||
|
225, 248, 152, 17, 105, 217, 142, 148,
|
||||||
|
155, 30, 135, 233, 206, 85, 40, 223,
|
||||||
|
140, 161, 137, 13, 191, 230, 66, 104,
|
||||||
|
65, 153, 45, 15, 176, 84, 187, 22
|
||||||
|
};
|
||||||
|
|
||||||
|
// The inverse S-box
|
||||||
|
private static readonly byte[] Si = {
|
||||||
|
82, 9, 106, 213, 48, 54, 165, 56,
|
||||||
|
191, 64, 163, 158, 129, 243, 215, 251,
|
||||||
|
124, 227, 57, 130, 155, 47, 255, 135,
|
||||||
|
52, 142, 67, 68, 196, 222, 233, 203,
|
||||||
|
84, 123, 148, 50, 166, 194, 35, 61,
|
||||||
|
238, 76, 149, 11, 66, 250, 195, 78,
|
||||||
|
8, 46, 161, 102, 40, 217, 36, 178,
|
||||||
|
118, 91, 162, 73, 109, 139, 209, 37,
|
||||||
|
114, 248, 246, 100, 134, 104, 152, 22,
|
||||||
|
212, 164, 92, 204, 93, 101, 182, 146,
|
||||||
|
108, 112, 72, 80, 253, 237, 185, 218,
|
||||||
|
94, 21, 70, 87, 167, 141, 157, 132,
|
||||||
|
144, 216, 171, 0, 140, 188, 211, 10,
|
||||||
|
247, 228, 88, 5, 184, 179, 69, 6,
|
||||||
|
208, 44, 30, 143, 202, 63, 15, 2,
|
||||||
|
193, 175, 189, 3, 1, 19, 138, 107,
|
||||||
|
58, 145, 17, 65, 79, 103, 220, 234,
|
||||||
|
151, 242, 207, 206, 240, 180, 230, 115,
|
||||||
|
150, 172, 116, 34, 231, 173, 53, 133,
|
||||||
|
226, 249, 55, 232, 28, 117, 223, 110,
|
||||||
|
71, 241, 26, 113, 29, 41, 197, 137,
|
||||||
|
111, 183, 98, 14, 170, 24, 190, 27,
|
||||||
|
252, 86, 62, 75, 198, 210, 121, 32,
|
||||||
|
154, 219, 192, 254, 120, 205, 90, 244,
|
||||||
|
31, 221, 168, 51, 136, 7, 199, 49,
|
||||||
|
177, 18, 16, 89, 39, 128, 236, 95,
|
||||||
|
96, 81, 127, 169, 25, 181, 74, 13,
|
||||||
|
45, 229, 122, 159, 147, 201, 156, 239,
|
||||||
|
160, 224, 59, 77, 174, 42, 245, 176,
|
||||||
|
200, 235, 187, 60, 131, 83, 153, 97,
|
||||||
|
23, 43, 4, 126, 186, 119, 214, 38,
|
||||||
|
225, 105, 20, 99, 85, 33, 12, 125
|
||||||
|
};
|
||||||
|
|
||||||
|
// vector used in calculating key schedule (powers of x in GF(256))
|
||||||
|
private static readonly byte[] rcon = {
|
||||||
|
0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
|
||||||
|
0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91
|
||||||
|
};
|
||||||
|
|
||||||
|
// precomputation tables of calculations for rounds
|
||||||
|
private static readonly uint[] T0 = {
|
||||||
|
0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff,
|
||||||
|
0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102,
|
||||||
|
0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d,
|
||||||
|
0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa,
|
||||||
|
0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41,
|
||||||
|
0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453,
|
||||||
|
0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d,
|
||||||
|
0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83,
|
||||||
|
0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2,
|
||||||
|
0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795,
|
||||||
|
0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a,
|
||||||
|
0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df,
|
||||||
|
0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912,
|
||||||
|
0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc,
|
||||||
|
0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7,
|
||||||
|
0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413,
|
||||||
|
0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040,
|
||||||
|
0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d,
|
||||||
|
0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0,
|
||||||
|
0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed,
|
||||||
|
0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a,
|
||||||
|
0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78,
|
||||||
|
0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080,
|
||||||
|
0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1,
|
||||||
|
0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020,
|
||||||
|
0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18,
|
||||||
|
0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488,
|
||||||
|
0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a,
|
||||||
|
0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0,
|
||||||
|
0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54,
|
||||||
|
0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b,
|
||||||
|
0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad,
|
||||||
|
0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992,
|
||||||
|
0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd,
|
||||||
|
0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3,
|
||||||
|
0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda,
|
||||||
|
0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8,
|
||||||
|
0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4,
|
||||||
|
0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a,
|
||||||
|
0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697,
|
||||||
|
0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96,
|
||||||
|
0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c,
|
||||||
|
0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7,
|
||||||
|
0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969,
|
||||||
|
0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9,
|
||||||
|
0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9,
|
||||||
|
0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715,
|
||||||
|
0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5,
|
||||||
|
0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65,
|
||||||
|
0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929,
|
||||||
|
0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d,
|
||||||
|
0x3a16162c
|
||||||
|
};
|
||||||
|
|
||||||
|
private static readonly uint[] Tinv0 = {
|
||||||
|
0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b,
|
||||||
|
0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad,
|
||||||
|
0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526,
|
||||||
|
0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d,
|
||||||
|
0x02752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03,
|
||||||
|
0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458,
|
||||||
|
0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899,
|
||||||
|
0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d,
|
||||||
|
0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1,
|
||||||
|
0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f,
|
||||||
|
0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3,
|
||||||
|
0x2aab5566, 0x0728ebb2, 0x03c2b52f, 0x9a7bc586, 0xa50837d3,
|
||||||
|
0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a,
|
||||||
|
0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506,
|
||||||
|
0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05,
|
||||||
|
0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x069f715e, 0x51106ebd,
|
||||||
|
0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491,
|
||||||
|
0x055dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6,
|
||||||
|
0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7,
|
||||||
|
0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x00000000,
|
||||||
|
0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd,
|
||||||
|
0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68,
|
||||||
|
0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0x0fe75793, 0xd296eeb4,
|
||||||
|
0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c,
|
||||||
|
0x0aba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0x0b0d090e,
|
||||||
|
0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af,
|
||||||
|
0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644,
|
||||||
|
0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8,
|
||||||
|
0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85,
|
||||||
|
0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc,
|
||||||
|
0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411,
|
||||||
|
0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322,
|
||||||
|
0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6,
|
||||||
|
0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0x0d927850,
|
||||||
|
0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e,
|
||||||
|
0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf,
|
||||||
|
0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x097826cd,
|
||||||
|
0xf418596e, 0x01b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa,
|
||||||
|
0x08cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea,
|
||||||
|
0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235,
|
||||||
|
0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1,
|
||||||
|
0xf7daec41, 0x0e50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43,
|
||||||
|
0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1,
|
||||||
|
0x7f516546, 0x04ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb,
|
||||||
|
0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a,
|
||||||
|
0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7,
|
||||||
|
0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418,
|
||||||
|
0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478,
|
||||||
|
0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16,
|
||||||
|
0x0c25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08,
|
||||||
|
0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48,
|
||||||
|
0x4257b8d0
|
||||||
|
};
|
||||||
|
|
||||||
|
private uint C0, C1, C2, C3;
|
||||||
|
private int ROUNDS;
|
||||||
|
private uint[,] WorkingKey;
|
||||||
|
private bool forEncryption;
|
||||||
|
|
||||||
|
public string AlgorithmName {
|
||||||
|
get { return "AES"; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsPartialBlockOkay {
|
||||||
|
get { return false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private uint Shift(
|
||||||
|
uint r,
|
||||||
|
int shift) {
|
||||||
|
return (r >> shift) | (r << (32 - shift));
|
||||||
|
}
|
||||||
|
|
||||||
|
private uint FFmulX(
|
||||||
|
uint x) {
|
||||||
|
return ((x & m2) << 1) ^ (((x & m1) >> 7)*m3);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
The following defines provide alternative definitions of FFmulX that might
|
||||||
|
give improved performance if a fast 32-bit multiply is not available.
|
||||||
|
|
||||||
|
private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); }
|
||||||
|
private static final int m4 = 0x1b1b1b1b;
|
||||||
|
private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); }
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
private uint Inv_Mcol(
|
||||||
|
uint x) {
|
||||||
|
uint f2 = FFmulX(x);
|
||||||
|
uint f4 = FFmulX(f2);
|
||||||
|
uint f8 = FFmulX(f4);
|
||||||
|
uint f9 = x ^ f8;
|
||||||
|
|
||||||
|
return f2 ^ f4 ^ f8 ^ Shift(f2 ^ f9, 8) ^ Shift(f4 ^ f9, 16) ^ Shift(f9, 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
private uint SubWord(
|
||||||
|
uint x) {
|
||||||
|
return S[x & 255]
|
||||||
|
| (((uint) S[(x >> 8) & 255]) << 8)
|
||||||
|
| (((uint) S[(x >> 16) & 255]) << 16)
|
||||||
|
| (((uint) S[(x >> 24) & 255]) << 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculate the necessary round keys
|
||||||
|
* The number of calculations depends on key size and block size
|
||||||
|
* AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits
|
||||||
|
* This code is written assuming those are the only possible values
|
||||||
|
*/
|
||||||
|
|
||||||
|
private uint[,] GenerateWorkingKey(
|
||||||
|
byte[] key,
|
||||||
|
bool forEncryption) {
|
||||||
|
int KC = key.Length/4; // key length in words
|
||||||
|
int t;
|
||||||
|
|
||||||
|
if((KC != 4) && (KC != 6) && (KC != 8))
|
||||||
|
throw new ArgumentException("Key length not 128/192/256 bits.");
|
||||||
|
|
||||||
|
ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes
|
||||||
|
var W = new uint[ROUNDS + 1, 4]; // 4 words in a block
|
||||||
|
|
||||||
|
//
|
||||||
|
// copy the key into the round key array
|
||||||
|
//
|
||||||
|
|
||||||
|
t = 0;
|
||||||
|
for(int i = 0; i < key.Length; t++) {
|
||||||
|
W[t >> 2, t & 3] = Pack.LE_To_UInt32(key, i);
|
||||||
|
i += 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// while not enough round key material calculated
|
||||||
|
// calculate new values
|
||||||
|
//
|
||||||
|
int k = (ROUNDS + 1) << 2;
|
||||||
|
for(int i = KC; (i < k); i++) {
|
||||||
|
uint temp = W[(i - 1) >> 2, (i - 1) & 3];
|
||||||
|
if((i%KC) == 0) {
|
||||||
|
temp = SubWord(Shift(temp, 8)) ^ rcon[(i/KC) - 1];
|
||||||
|
} else if((KC > 6) && ((i%KC) == 4)) {
|
||||||
|
temp = SubWord(temp);
|
||||||
|
}
|
||||||
|
|
||||||
|
W[i >> 2, i & 3] = W[(i - KC) >> 2, (i - KC) & 3] ^ temp;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(!forEncryption) {
|
||||||
|
for(int j = 1; j < ROUNDS; j++) {
|
||||||
|
for(int i = 0; i < 4; i++) {
|
||||||
|
W[j, i] = Inv_Mcol(W[j, i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return W;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Init(bool forEncryption, byte[] key) {
|
||||||
|
WorkingKey = GenerateWorkingKey(key, forEncryption);
|
||||||
|
this.forEncryption = forEncryption;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int GetBlockSize() {
|
||||||
|
return BLOCK_SIZE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) {
|
||||||
|
if(WorkingKey == null) {
|
||||||
|
throw new InvalidOperationException("AES engine not initialised");
|
||||||
|
}
|
||||||
|
|
||||||
|
if((inOff + (32/2)) > input.Length) {
|
||||||
|
throw new InvalidOperationException("input buffer too short");
|
||||||
|
}
|
||||||
|
|
||||||
|
if((outOff + (32/2)) > output.Length) {
|
||||||
|
throw new InvalidOperationException("output buffer too short");
|
||||||
|
}
|
||||||
|
|
||||||
|
UnPackBlock(input, inOff);
|
||||||
|
|
||||||
|
if(forEncryption) {
|
||||||
|
EncryptBlock(WorkingKey);
|
||||||
|
} else {
|
||||||
|
DecryptBlock(WorkingKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
PackBlock(output, outOff);
|
||||||
|
|
||||||
|
return BLOCK_SIZE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Reset() {
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UnPackBlock(
|
||||||
|
byte[] bytes,
|
||||||
|
int off) {
|
||||||
|
C0 = Pack.LE_To_UInt32(bytes, off);
|
||||||
|
C1 = Pack.LE_To_UInt32(bytes, off + 4);
|
||||||
|
C2 = Pack.LE_To_UInt32(bytes, off + 8);
|
||||||
|
C3 = Pack.LE_To_UInt32(bytes, off + 12);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void PackBlock(
|
||||||
|
byte[] bytes,
|
||||||
|
int off) {
|
||||||
|
Pack.UInt32_To_LE(C0, bytes, off);
|
||||||
|
Pack.UInt32_To_LE(C1, bytes, off + 4);
|
||||||
|
Pack.UInt32_To_LE(C2, bytes, off + 8);
|
||||||
|
Pack.UInt32_To_LE(C3, bytes, off + 12);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EncryptBlock(
|
||||||
|
uint[,] KW) {
|
||||||
|
uint r, r0, r1, r2, r3;
|
||||||
|
|
||||||
|
C0 ^= KW[0, 0];
|
||||||
|
C1 ^= KW[0, 1];
|
||||||
|
C2 ^= KW[0, 2];
|
||||||
|
C3 ^= KW[0, 3];
|
||||||
|
|
||||||
|
for(r = 1; r < ROUNDS - 1;) {
|
||||||
|
r0 = T0[C0 & 255] ^ Shift(T0[(C1 >> 8) & 255], 24) ^ Shift(T0[(C2 >> 16) & 255], 16) ^
|
||||||
|
Shift(T0[(C3 >> 24) & 255], 8) ^ KW[r, 0];
|
||||||
|
r1 = T0[C1 & 255] ^ Shift(T0[(C2 >> 8) & 255], 24) ^ Shift(T0[(C3 >> 16) & 255], 16) ^
|
||||||
|
Shift(T0[(C0 >> 24) & 255], 8) ^ KW[r, 1];
|
||||||
|
r2 = T0[C2 & 255] ^ Shift(T0[(C3 >> 8) & 255], 24) ^ Shift(T0[(C0 >> 16) & 255], 16) ^
|
||||||
|
Shift(T0[(C1 >> 24) & 255], 8) ^ KW[r, 2];
|
||||||
|
r3 = T0[C3 & 255] ^ Shift(T0[(C0 >> 8) & 255], 24) ^ Shift(T0[(C1 >> 16) & 255], 16) ^
|
||||||
|
Shift(T0[(C2 >> 24) & 255], 8) ^ KW[r++, 3];
|
||||||
|
C0 = T0[r0 & 255] ^ Shift(T0[(r1 >> 8) & 255], 24) ^ Shift(T0[(r2 >> 16) & 255], 16) ^
|
||||||
|
Shift(T0[(r3 >> 24) & 255], 8) ^ KW[r, 0];
|
||||||
|
C1 = T0[r1 & 255] ^ Shift(T0[(r2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^
|
||||||
|
Shift(T0[(r0 >> 24) & 255], 8) ^ KW[r, 1];
|
||||||
|
C2 = T0[r2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(r0 >> 16) & 255], 16) ^
|
||||||
|
Shift(T0[(r1 >> 24) & 255], 8) ^ KW[r, 2];
|
||||||
|
C3 = T0[r3 & 255] ^ Shift(T0[(r0 >> 8) & 255], 24) ^ Shift(T0[(r1 >> 16) & 255], 16) ^
|
||||||
|
Shift(T0[(r2 >> 24) & 255], 8) ^ KW[r++, 3];
|
||||||
|
}
|
||||||
|
|
||||||
|
r0 = T0[C0 & 255] ^ Shift(T0[(C1 >> 8) & 255], 24) ^ Shift(T0[(C2 >> 16) & 255], 16) ^
|
||||||
|
Shift(T0[(C3 >> 24) & 255], 8) ^ KW[r, 0];
|
||||||
|
r1 = T0[C1 & 255] ^ Shift(T0[(C2 >> 8) & 255], 24) ^ Shift(T0[(C3 >> 16) & 255], 16) ^
|
||||||
|
Shift(T0[(C0 >> 24) & 255], 8) ^ KW[r, 1];
|
||||||
|
r2 = T0[C2 & 255] ^ Shift(T0[(C3 >> 8) & 255], 24) ^ Shift(T0[(C0 >> 16) & 255], 16) ^
|
||||||
|
Shift(T0[(C1 >> 24) & 255], 8) ^ KW[r, 2];
|
||||||
|
r3 = T0[C3 & 255] ^ Shift(T0[(C0 >> 8) & 255], 24) ^ Shift(T0[(C1 >> 16) & 255], 16) ^
|
||||||
|
Shift(T0[(C2 >> 24) & 255], 8) ^ KW[r++, 3];
|
||||||
|
|
||||||
|
// the final round's table is a simple function of S so we don't use a whole other four tables for it
|
||||||
|
|
||||||
|
C0 = S[r0 & 255] ^ (((uint) S[(r1 >> 8) & 255]) << 8) ^ (((uint) S[(r2 >> 16) & 255]) << 16) ^
|
||||||
|
(((uint) S[(r3 >> 24) & 255]) << 24) ^ KW[r, 0];
|
||||||
|
C1 = S[r1 & 255] ^ (((uint) S[(r2 >> 8) & 255]) << 8) ^ (((uint) S[(r3 >> 16) & 255]) << 16) ^
|
||||||
|
(((uint) S[(r0 >> 24) & 255]) << 24) ^ KW[r, 1];
|
||||||
|
C2 = S[r2 & 255] ^ (((uint) S[(r3 >> 8) & 255]) << 8) ^ (((uint) S[(r0 >> 16) & 255]) << 16) ^
|
||||||
|
(((uint) S[(r1 >> 24) & 255]) << 24) ^ KW[r, 2];
|
||||||
|
C3 = S[r3 & 255] ^ (((uint) S[(r0 >> 8) & 255]) << 8) ^ (((uint) S[(r1 >> 16) & 255]) << 16) ^
|
||||||
|
(((uint) S[(r2 >> 24) & 255]) << 24) ^ KW[r, 3];
|
||||||
|
}
|
||||||
|
|
||||||
|
private void DecryptBlock(
|
||||||
|
uint[,] KW) {
|
||||||
|
int r;
|
||||||
|
uint r0, r1, r2, r3;
|
||||||
|
|
||||||
|
C0 ^= KW[ROUNDS, 0];
|
||||||
|
C1 ^= KW[ROUNDS, 1];
|
||||||
|
C2 ^= KW[ROUNDS, 2];
|
||||||
|
C3 ^= KW[ROUNDS, 3];
|
||||||
|
|
||||||
|
for(r = ROUNDS - 1; r > 1;) {
|
||||||
|
r0 = Tinv0[C0 & 255] ^ Shift(Tinv0[(C3 >> 8) & 255], 24) ^ Shift(Tinv0[(C2 >> 16) & 255], 16) ^
|
||||||
|
Shift(Tinv0[(C1 >> 24) & 255], 8) ^ KW[r, 0];
|
||||||
|
r1 = Tinv0[C1 & 255] ^ Shift(Tinv0[(C0 >> 8) & 255], 24) ^ Shift(Tinv0[(C3 >> 16) & 255], 16) ^
|
||||||
|
Shift(Tinv0[(C2 >> 24) & 255], 8) ^ KW[r, 1];
|
||||||
|
r2 = Tinv0[C2 & 255] ^ Shift(Tinv0[(C1 >> 8) & 255], 24) ^ Shift(Tinv0[(C0 >> 16) & 255], 16) ^
|
||||||
|
Shift(Tinv0[(C3 >> 24) & 255], 8) ^ KW[r, 2];
|
||||||
|
r3 = Tinv0[C3 & 255] ^ Shift(Tinv0[(C2 >> 8) & 255], 24) ^ Shift(Tinv0[(C1 >> 16) & 255], 16) ^
|
||||||
|
Shift(Tinv0[(C0 >> 24) & 255], 8) ^ KW[r--, 3];
|
||||||
|
C0 = Tinv0[r0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(r2 >> 16) & 255], 16) ^
|
||||||
|
Shift(Tinv0[(r1 >> 24) & 255], 8) ^ KW[r, 0];
|
||||||
|
C1 = Tinv0[r1 & 255] ^ Shift(Tinv0[(r0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^
|
||||||
|
Shift(Tinv0[(r2 >> 24) & 255], 8) ^ KW[r, 1];
|
||||||
|
C2 = Tinv0[r2 & 255] ^ Shift(Tinv0[(r1 >> 8) & 255], 24) ^ Shift(Tinv0[(r0 >> 16) & 255], 16) ^
|
||||||
|
Shift(Tinv0[(r3 >> 24) & 255], 8) ^ KW[r, 2];
|
||||||
|
C3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(r2 >> 8) & 255], 24) ^ Shift(Tinv0[(r1 >> 16) & 255], 16) ^
|
||||||
|
Shift(Tinv0[(r0 >> 24) & 255], 8) ^ KW[r--, 3];
|
||||||
|
}
|
||||||
|
|
||||||
|
r0 = Tinv0[C0 & 255] ^ Shift(Tinv0[(C3 >> 8) & 255], 24) ^ Shift(Tinv0[(C2 >> 16) & 255], 16) ^
|
||||||
|
Shift(Tinv0[(C1 >> 24) & 255], 8) ^ KW[r, 0];
|
||||||
|
r1 = Tinv0[C1 & 255] ^ Shift(Tinv0[(C0 >> 8) & 255], 24) ^ Shift(Tinv0[(C3 >> 16) & 255], 16) ^
|
||||||
|
Shift(Tinv0[(C2 >> 24) & 255], 8) ^ KW[r, 1];
|
||||||
|
r2 = Tinv0[C2 & 255] ^ Shift(Tinv0[(C1 >> 8) & 255], 24) ^ Shift(Tinv0[(C0 >> 16) & 255], 16) ^
|
||||||
|
Shift(Tinv0[(C3 >> 24) & 255], 8) ^ KW[r, 2];
|
||||||
|
r3 = Tinv0[C3 & 255] ^ Shift(Tinv0[(C2 >> 8) & 255], 24) ^ Shift(Tinv0[(C1 >> 16) & 255], 16) ^
|
||||||
|
Shift(Tinv0[(C0 >> 24) & 255], 8) ^ KW[r, 3];
|
||||||
|
|
||||||
|
// the final round's table is a simple function of Si so we don't use a whole other four tables for it
|
||||||
|
|
||||||
|
C0 = Si[r0 & 255] ^ (((uint) Si[(r3 >> 8) & 255]) << 8) ^ (((uint) Si[(r2 >> 16) & 255]) << 16) ^
|
||||||
|
(((uint) Si[(r1 >> 24) & 255]) << 24) ^ KW[0, 0];
|
||||||
|
C1 = Si[r1 & 255] ^ (((uint) Si[(r0 >> 8) & 255]) << 8) ^ (((uint) Si[(r3 >> 16) & 255]) << 16) ^
|
||||||
|
(((uint) Si[(r2 >> 24) & 255]) << 24) ^ KW[0, 1];
|
||||||
|
C2 = Si[r2 & 255] ^ (((uint) Si[(r1 >> 8) & 255]) << 8) ^ (((uint) Si[(r0 >> 16) & 255]) << 16) ^
|
||||||
|
(((uint) Si[(r3 >> 24) & 255]) << 24) ^ KW[0, 2];
|
||||||
|
C3 = Si[r3 & 255] ^ (((uint) Si[(r2 >> 8) & 255]) << 8) ^ (((uint) Si[(r1 >> 16) & 255]) << 16) ^
|
||||||
|
(((uint) Si[(r0 >> 24) & 255]) << 24) ^ KW[0, 3];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
internal sealed class Pack {
|
||||||
|
private Pack() {
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void UInt32_To_BE(uint n, byte[] bs) {
|
||||||
|
bs[0] = (byte) (n >> 24);
|
||||||
|
bs[1] = (byte) (n >> 16);
|
||||||
|
bs[2] = (byte) (n >> 8);
|
||||||
|
bs[3] = (byte) (n);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void UInt32_To_BE(uint n, byte[] bs, int off) {
|
||||||
|
bs[off] = (byte) (n >> 24);
|
||||||
|
bs[++off] = (byte) (n >> 16);
|
||||||
|
bs[++off] = (byte) (n >> 8);
|
||||||
|
bs[++off] = (byte) (n);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static uint BE_To_UInt32(byte[] bs) {
|
||||||
|
uint n = (uint) bs[0] << 24;
|
||||||
|
n |= (uint) bs[1] << 16;
|
||||||
|
n |= (uint) bs[2] << 8;
|
||||||
|
n |= bs[3];
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static uint BE_To_UInt32(byte[] bs, int off) {
|
||||||
|
uint n = (uint) bs[off] << 24;
|
||||||
|
n |= (uint) bs[++off] << 16;
|
||||||
|
n |= (uint) bs[++off] << 8;
|
||||||
|
n |= bs[++off];
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static ulong BE_To_UInt64(byte[] bs) {
|
||||||
|
uint hi = BE_To_UInt32(bs);
|
||||||
|
uint lo = BE_To_UInt32(bs, 4);
|
||||||
|
return ((ulong) hi << 32) | lo;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static ulong BE_To_UInt64(byte[] bs, int off) {
|
||||||
|
uint hi = BE_To_UInt32(bs, off);
|
||||||
|
uint lo = BE_To_UInt32(bs, off + 4);
|
||||||
|
return ((ulong) hi << 32) | lo;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void UInt64_To_BE(ulong n, byte[] bs) {
|
||||||
|
UInt32_To_BE((uint) (n >> 32), bs);
|
||||||
|
UInt32_To_BE((uint) (n), bs, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void UInt64_To_BE(ulong n, byte[] bs, int off) {
|
||||||
|
UInt32_To_BE((uint) (n >> 32), bs, off);
|
||||||
|
UInt32_To_BE((uint) (n), bs, off + 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void UInt32_To_LE(uint n, byte[] bs) {
|
||||||
|
bs[0] = (byte) (n);
|
||||||
|
bs[1] = (byte) (n >> 8);
|
||||||
|
bs[2] = (byte) (n >> 16);
|
||||||
|
bs[3] = (byte) (n >> 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void UInt32_To_LE(uint n, byte[] bs, int off) {
|
||||||
|
bs[off] = (byte) (n);
|
||||||
|
bs[++off] = (byte) (n >> 8);
|
||||||
|
bs[++off] = (byte) (n >> 16);
|
||||||
|
bs[++off] = (byte) (n >> 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static uint LE_To_UInt32(byte[] bs) {
|
||||||
|
uint n = bs[0];
|
||||||
|
n |= (uint) bs[1] << 8;
|
||||||
|
n |= (uint) bs[2] << 16;
|
||||||
|
n |= (uint) bs[3] << 24;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static uint LE_To_UInt32(byte[] bs, int off) {
|
||||||
|
uint n = bs[off];
|
||||||
|
n |= (uint) bs[++off] << 8;
|
||||||
|
n |= (uint) bs[++off] << 16;
|
||||||
|
n |= (uint) bs[++off] << 24;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static ulong LE_To_UInt64(byte[] bs) {
|
||||||
|
uint lo = LE_To_UInt32(bs);
|
||||||
|
uint hi = LE_To_UInt32(bs, 4);
|
||||||
|
return ((ulong) hi << 32) | lo;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static ulong LE_To_UInt64(byte[] bs, int off) {
|
||||||
|
uint lo = LE_To_UInt32(bs, off);
|
||||||
|
uint hi = LE_To_UInt32(bs, off + 4);
|
||||||
|
return ((ulong) hi << 32) | lo;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void UInt64_To_LE(ulong n, byte[] bs) {
|
||||||
|
UInt32_To_LE((uint) (n), bs);
|
||||||
|
UInt32_To_LE((uint) (n >> 32), bs, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void UInt64_To_LE(ulong n, byte[] bs, int off) {
|
||||||
|
UInt32_To_LE((uint) (n), bs, off);
|
||||||
|
UInt32_To_LE((uint) (n >> 32), bs, off + 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
68
TLSharp.Core/MTProto/Crypto/AuthKey.cs
Normal file
68
TLSharp.Core/MTProto/Crypto/AuthKey.cs
Normal file
|
|
@ -0,0 +1,68 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.MTProto.Crypto {
|
||||||
|
public class AuthKey {
|
||||||
|
private byte[] key;
|
||||||
|
private ulong keyId;
|
||||||
|
private ulong auxHash;
|
||||||
|
public AuthKey(BigInteger gab) {
|
||||||
|
key = gab.ToByteArrayUnsigned();
|
||||||
|
using(SHA1 hash = new SHA1Managed()) {
|
||||||
|
using(MemoryStream hashStream = new MemoryStream(hash.ComputeHash(key), false)) {
|
||||||
|
using(BinaryReader hashReader = new BinaryReader(hashStream)) {
|
||||||
|
auxHash = hashReader.ReadUInt64();
|
||||||
|
hashReader.ReadBytes(4);
|
||||||
|
keyId = hashReader.ReadUInt64();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public AuthKey(byte[] data) {
|
||||||
|
key = data;
|
||||||
|
using (SHA1 hash = new SHA1Managed()) {
|
||||||
|
using (MemoryStream hashStream = new MemoryStream(hash.ComputeHash(key), false)) {
|
||||||
|
using (BinaryReader hashReader = new BinaryReader(hashStream)) {
|
||||||
|
auxHash = hashReader.ReadUInt64();
|
||||||
|
hashReader.ReadBytes(4);
|
||||||
|
keyId = hashReader.ReadUInt64();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] CalcNewNonceHash(byte[] newNonce, int number) {
|
||||||
|
using(MemoryStream buffer = new MemoryStream(100)) {
|
||||||
|
using(BinaryWriter bufferWriter = new BinaryWriter(buffer)) {
|
||||||
|
bufferWriter.Write(newNonce);
|
||||||
|
bufferWriter.Write((byte)number);
|
||||||
|
bufferWriter.Write(auxHash);
|
||||||
|
using(SHA1 sha1 = new SHA1Managed()) {
|
||||||
|
byte[] hash = sha1.ComputeHash(buffer.GetBuffer(), 0, (int)buffer.Position);
|
||||||
|
byte[] newNonceHash = new byte[16];
|
||||||
|
Array.Copy(hash, 4, newNonceHash, 0, 16);
|
||||||
|
return newNonceHash;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] Data {
|
||||||
|
get {
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public ulong Id {
|
||||||
|
get {
|
||||||
|
return keyId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString() {
|
||||||
|
return string.Format("(Key: {0}, KeyId: {1}, AuxHash: {2})", key, keyId, auxHash);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
2823
TLSharp.Core/MTProto/Crypto/BigInteger.cs
Normal file
2823
TLSharp.Core/MTProto/Crypto/BigInteger.cs
Normal file
File diff suppressed because it is too large
Load diff
104
TLSharp.Core/MTProto/Crypto/Crc32.cs
Normal file
104
TLSharp.Core/MTProto/Crypto/Crc32.cs
Normal file
|
|
@ -0,0 +1,104 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Ionic.Crc;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.MTProto.Crypto {
|
||||||
|
public class Crc32 : HashAlgorithm {
|
||||||
|
public const UInt32 DefaultPolynomial = 0xedb88320u;
|
||||||
|
public const UInt32 DefaultSeed = 0xffffffffu;
|
||||||
|
|
||||||
|
private UInt32 hash;
|
||||||
|
private UInt32 seed;
|
||||||
|
private UInt32[] table;
|
||||||
|
private static UInt32[] defaultTable;
|
||||||
|
|
||||||
|
public Crc32() {
|
||||||
|
table = InitializeTable(DefaultPolynomial);
|
||||||
|
seed = DefaultSeed;
|
||||||
|
hash = seed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Crc32(UInt32 polynomial, UInt32 seed) {
|
||||||
|
table = InitializeTable(polynomial);
|
||||||
|
this.seed = seed;
|
||||||
|
hash = seed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Initialize() {
|
||||||
|
hash = seed;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void HashCore(byte[] buffer, int start, int length) {
|
||||||
|
hash = CalculateHash(table, hash, buffer, start, length);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Возвращает хеш в BigEndian
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
protected override byte[] HashFinal() {
|
||||||
|
byte[] hashBuffer = UInt32ToBigEndianBytes(~hash);
|
||||||
|
this.HashValue = hashBuffer;
|
||||||
|
return hashBuffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override int HashSize {
|
||||||
|
get { return 32; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public static UInt32 Compute(byte[] buffer) {
|
||||||
|
return ~CalculateHash(InitializeTable(DefaultPolynomial), DefaultSeed, buffer, 0, buffer.Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static UInt32 Compute(UInt32 seed, byte[] buffer) {
|
||||||
|
return ~CalculateHash(InitializeTable(DefaultPolynomial), seed, buffer, 0, buffer.Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static UInt32 Compute(UInt32 polynomial, UInt32 seed, byte[] buffer) {
|
||||||
|
return ~CalculateHash(InitializeTable(polynomial), seed, buffer, 0, buffer.Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static UInt32[] InitializeTable(UInt32 polynomial) {
|
||||||
|
if (polynomial == DefaultPolynomial && defaultTable != null)
|
||||||
|
return defaultTable;
|
||||||
|
|
||||||
|
UInt32[] createTable = new UInt32[256];
|
||||||
|
for (int i = 0; i < 256; i++) {
|
||||||
|
UInt32 entry = (UInt32)i;
|
||||||
|
for (int j = 0; j < 8; j++)
|
||||||
|
if ((entry & 1) == 1)
|
||||||
|
entry = (entry >> 1) ^ polynomial;
|
||||||
|
else
|
||||||
|
entry = entry >> 1;
|
||||||
|
createTable[i] = entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (polynomial == DefaultPolynomial)
|
||||||
|
defaultTable = createTable;
|
||||||
|
|
||||||
|
return createTable;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static UInt32 CalculateHash(UInt32[] table, UInt32 seed, byte[] buffer, int start, int size) {
|
||||||
|
UInt32 crc = seed;
|
||||||
|
for (int i = start; i < size; i++)
|
||||||
|
unchecked {
|
||||||
|
crc = (crc >> 8) ^ table[buffer[i] ^ crc & 0xff];
|
||||||
|
}
|
||||||
|
return crc;
|
||||||
|
}
|
||||||
|
|
||||||
|
private byte[] UInt32ToBigEndianBytes(UInt32 x) {
|
||||||
|
return new byte[] {
|
||||||
|
(byte)((x >> 24) & 0xff),
|
||||||
|
(byte)((x >> 16) & 0xff),
|
||||||
|
(byte)((x >> 8) & 0xff),
|
||||||
|
(byte)(x & 0xff)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
110
TLSharp.Core/MTProto/Crypto/Factorizator.cs
Normal file
110
TLSharp.Core/MTProto/Crypto/Factorizator.cs
Normal file
|
|
@ -0,0 +1,110 @@
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.MTProto.Crypto {
|
||||||
|
public class FactorizedPair {
|
||||||
|
private readonly BigInteger p;
|
||||||
|
private readonly BigInteger q;
|
||||||
|
|
||||||
|
public FactorizedPair(BigInteger p, BigInteger q) {
|
||||||
|
this.p = p;
|
||||||
|
this.q = q;
|
||||||
|
}
|
||||||
|
|
||||||
|
public FactorizedPair(long p, long q) {
|
||||||
|
this.p = BigInteger.ValueOf(p);
|
||||||
|
this.q = BigInteger.ValueOf(q);
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger Min {
|
||||||
|
get {
|
||||||
|
return p.Min(q);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger Max {
|
||||||
|
get {
|
||||||
|
return p.Max(q);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString() {
|
||||||
|
return string.Format("P: {0}, Q: {1}", p, q);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public class Factorizator {
|
||||||
|
public static Random random = new Random();
|
||||||
|
public static long findSmallMultiplierLopatin(long what) {
|
||||||
|
long g = 0;
|
||||||
|
for (int i = 0; i < 3; i++) {
|
||||||
|
int q = (random.Next(128) & 15) + 17;
|
||||||
|
long x = random.Next(1000000000) + 1, y = x;
|
||||||
|
int lim = 1 << (i + 18);
|
||||||
|
for (int j = 1; j < lim; j++) {
|
||||||
|
long a = x, b = x, c = q;
|
||||||
|
while (b != 0) {
|
||||||
|
if ((b & 1) != 0) {
|
||||||
|
c += a;
|
||||||
|
if (c >= what) {
|
||||||
|
c -= what;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
a += a;
|
||||||
|
if (a >= what) {
|
||||||
|
a -= what;
|
||||||
|
}
|
||||||
|
b >>= 1;
|
||||||
|
}
|
||||||
|
x = c;
|
||||||
|
long z = x < y ? y - x : x - y;
|
||||||
|
g = GCD(z, what);
|
||||||
|
if (g != 1) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if ((j & (j - 1)) == 0) {
|
||||||
|
y = x;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (g > 1) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
long p = what / g;
|
||||||
|
return Math.Min(p, g);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static long GCD(long a, long b) {
|
||||||
|
while (a != 0 && b != 0) {
|
||||||
|
while ((b & 1) == 0) {
|
||||||
|
b >>= 1;
|
||||||
|
}
|
||||||
|
while ((a & 1) == 0) {
|
||||||
|
a >>= 1;
|
||||||
|
}
|
||||||
|
if (a > b) {
|
||||||
|
a -= b;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
b -= a;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return b == 0 ? a : b;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static FactorizedPair Factorize(BigInteger pq) {
|
||||||
|
if(pq.BitLength < 64) {
|
||||||
|
long pqlong = pq.LongValue;
|
||||||
|
long divisor = findSmallMultiplierLopatin(pqlong);
|
||||||
|
return new FactorizedPair(BigInteger.ValueOf(divisor), BigInteger.ValueOf(pqlong/divisor));
|
||||||
|
} else {
|
||||||
|
// TODO: port pollard factorization
|
||||||
|
throw new InvalidOperationException("pq too long; TODO: port the pollard algo");
|
||||||
|
// logger.error("pq too long; TODO: port the pollard algo");
|
||||||
|
// return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
463
TLSharp.Core/MTProto/Crypto/MD5Digest.cs
Normal file
463
TLSharp.Core/MTProto/Crypto/MD5Digest.cs
Normal file
|
|
@ -0,0 +1,463 @@
|
||||||
|
using System;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.MTProto.Crypto {
|
||||||
|
public interface IDigest {
|
||||||
|
/**
|
||||||
|
* return the algorithm name
|
||||||
|
*
|
||||||
|
* @return the algorithm name
|
||||||
|
*/
|
||||||
|
string AlgorithmName { get; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* return the size, in bytes, of the digest produced by this message digest.
|
||||||
|
*
|
||||||
|
* @return the size, in bytes, of the digest produced by this message digest.
|
||||||
|
*/
|
||||||
|
int GetDigestSize();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* return the size, in bytes, of the internal buffer used by this digest.
|
||||||
|
*
|
||||||
|
* @return the size, in bytes, of the internal buffer used by this digest.
|
||||||
|
*/
|
||||||
|
int GetByteLength();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* update the message digest with a single byte.
|
||||||
|
*
|
||||||
|
* @param inByte the input byte to be entered.
|
||||||
|
*/
|
||||||
|
void Update(byte input);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* update the message digest with a block of bytes.
|
||||||
|
*
|
||||||
|
* @param input the byte array containing the data.
|
||||||
|
* @param inOff the offset into the byte array where the data starts.
|
||||||
|
* @param len the length of the data.
|
||||||
|
*/
|
||||||
|
void BlockUpdate(byte[] input, int inOff, int length);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Close the digest, producing the final digest value. The doFinal
|
||||||
|
* call leaves the digest reset.
|
||||||
|
*
|
||||||
|
* @param output the array the digest is to be copied into.
|
||||||
|
* @param outOff the offset into the out array the digest is to start at.
|
||||||
|
*/
|
||||||
|
int DoFinal(byte[] output, int outOff);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* reset the digest back to it's initial state.
|
||||||
|
*/
|
||||||
|
void Reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
public class MD5 {
|
||||||
|
|
||||||
|
public static string GetMd5String(string data) {
|
||||||
|
return BitConverter.ToString(GetMd5Bytes(Encoding.UTF8.GetBytes(data))).Replace("-", "").ToLower();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] GetMd5Bytes(byte[] data) {
|
||||||
|
MD5Digest digest = new MD5Digest();
|
||||||
|
digest.BlockUpdate(data, 0, data.Length);
|
||||||
|
byte[] hash = new byte[16];
|
||||||
|
digest.DoFinal(hash, 0);
|
||||||
|
|
||||||
|
return hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
private MD5Digest digest = new MD5Digest();
|
||||||
|
|
||||||
|
public void Update(byte[] chunk) {
|
||||||
|
digest.BlockUpdate(chunk, 0, chunk.Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Update(byte[] chunk, int offset, int limit) {
|
||||||
|
digest.BlockUpdate(chunk, offset, limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string FinalString() {
|
||||||
|
byte[] hash = new byte[16];
|
||||||
|
digest.DoFinal(hash, 0);
|
||||||
|
return BitConverter.ToString(hash).Replace("-", "").ToLower();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public abstract class GeneralDigest
|
||||||
|
: IDigest {
|
||||||
|
private const int BYTE_LENGTH = 64;
|
||||||
|
|
||||||
|
private readonly byte[] xBuf;
|
||||||
|
|
||||||
|
private long byteCount;
|
||||||
|
private int xBufOff;
|
||||||
|
|
||||||
|
internal GeneralDigest() {
|
||||||
|
xBuf = new byte[4];
|
||||||
|
}
|
||||||
|
|
||||||
|
internal GeneralDigest(GeneralDigest t) {
|
||||||
|
xBuf = new byte[t.xBuf.Length];
|
||||||
|
Array.Copy(t.xBuf, 0, xBuf, 0, t.xBuf.Length);
|
||||||
|
|
||||||
|
xBufOff = t.xBufOff;
|
||||||
|
byteCount = t.byteCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Update(byte input) {
|
||||||
|
xBuf[xBufOff++] = input;
|
||||||
|
|
||||||
|
if (xBufOff == xBuf.Length) {
|
||||||
|
ProcessWord(xBuf, 0);
|
||||||
|
xBufOff = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
byteCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void BlockUpdate(
|
||||||
|
byte[] input,
|
||||||
|
int inOff,
|
||||||
|
int length) {
|
||||||
|
//
|
||||||
|
// fill the current word
|
||||||
|
//
|
||||||
|
while ((xBufOff != 0) && (length > 0)) {
|
||||||
|
Update(input[inOff]);
|
||||||
|
inOff++;
|
||||||
|
length--;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// process whole words.
|
||||||
|
//
|
||||||
|
while (length > xBuf.Length) {
|
||||||
|
ProcessWord(input, inOff);
|
||||||
|
|
||||||
|
inOff += xBuf.Length;
|
||||||
|
length -= xBuf.Length;
|
||||||
|
byteCount += xBuf.Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// load in the remainder.
|
||||||
|
//
|
||||||
|
while (length > 0) {
|
||||||
|
Update(input[inOff]);
|
||||||
|
|
||||||
|
inOff++;
|
||||||
|
length--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual void Reset() {
|
||||||
|
byteCount = 0;
|
||||||
|
xBufOff = 0;
|
||||||
|
Array.Clear(xBuf, 0, xBuf.Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int GetByteLength() {
|
||||||
|
return BYTE_LENGTH;
|
||||||
|
}
|
||||||
|
|
||||||
|
public abstract string AlgorithmName { get; }
|
||||||
|
public abstract int GetDigestSize();
|
||||||
|
public abstract int DoFinal(byte[] output, int outOff);
|
||||||
|
|
||||||
|
public void Finish() {
|
||||||
|
long bitLength = (byteCount << 3);
|
||||||
|
|
||||||
|
//
|
||||||
|
// add the pad bytes.
|
||||||
|
//
|
||||||
|
Update(128);
|
||||||
|
|
||||||
|
while (xBufOff != 0) Update(0);
|
||||||
|
ProcessLength(bitLength);
|
||||||
|
ProcessBlock();
|
||||||
|
}
|
||||||
|
|
||||||
|
internal abstract void ProcessWord(byte[] input, int inOff);
|
||||||
|
internal abstract void ProcessLength(long bitLength);
|
||||||
|
internal abstract void ProcessBlock();
|
||||||
|
}
|
||||||
|
|
||||||
|
public class MD5Digest
|
||||||
|
: GeneralDigest {
|
||||||
|
private const int DigestLength = 16;
|
||||||
|
|
||||||
|
//
|
||||||
|
// round 1 left rotates
|
||||||
|
//
|
||||||
|
private static readonly int S11 = 7;
|
||||||
|
private static readonly int S12 = 12;
|
||||||
|
private static readonly int S13 = 17;
|
||||||
|
private static readonly int S14 = 22;
|
||||||
|
|
||||||
|
//
|
||||||
|
// round 2 left rotates
|
||||||
|
//
|
||||||
|
private static readonly int S21 = 5;
|
||||||
|
private static readonly int S22 = 9;
|
||||||
|
private static readonly int S23 = 14;
|
||||||
|
private static readonly int S24 = 20;
|
||||||
|
|
||||||
|
//
|
||||||
|
// round 3 left rotates
|
||||||
|
//
|
||||||
|
private static readonly int S31 = 4;
|
||||||
|
private static readonly int S32 = 11;
|
||||||
|
private static readonly int S33 = 16;
|
||||||
|
private static readonly int S34 = 23;
|
||||||
|
|
||||||
|
//
|
||||||
|
// round 4 left rotates
|
||||||
|
//
|
||||||
|
private static readonly int S41 = 6;
|
||||||
|
private static readonly int S42 = 10;
|
||||||
|
private static readonly int S43 = 15;
|
||||||
|
private static readonly int S44 = 21;
|
||||||
|
private readonly int[] X = new int[16];
|
||||||
|
private int H1, H2, H3, H4; // IV's
|
||||||
|
private int xOff;
|
||||||
|
|
||||||
|
public MD5Digest() {
|
||||||
|
Reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Copy constructor. This will copy the state of the provided
|
||||||
|
* message digest.
|
||||||
|
*/
|
||||||
|
|
||||||
|
public MD5Digest(MD5Digest t)
|
||||||
|
: base(t) {
|
||||||
|
H1 = t.H1;
|
||||||
|
H2 = t.H2;
|
||||||
|
H3 = t.H3;
|
||||||
|
H4 = t.H4;
|
||||||
|
|
||||||
|
Array.Copy(t.X, 0, X, 0, t.X.Length);
|
||||||
|
xOff = t.xOff;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string AlgorithmName {
|
||||||
|
get { return "MD5"; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public override int GetDigestSize() {
|
||||||
|
return DigestLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal override void ProcessWord(
|
||||||
|
byte[] input,
|
||||||
|
int inOff) {
|
||||||
|
X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8)
|
||||||
|
| ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24);
|
||||||
|
|
||||||
|
if (xOff == 16) {
|
||||||
|
ProcessBlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal override void ProcessLength(
|
||||||
|
long bitLength) {
|
||||||
|
if (xOff > 14) {
|
||||||
|
ProcessBlock();
|
||||||
|
}
|
||||||
|
|
||||||
|
X[14] = (int) (bitLength & 0xffffffff);
|
||||||
|
X[15] = (int) ((ulong) bitLength >> 32);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UnpackWord(
|
||||||
|
int word,
|
||||||
|
byte[] outBytes,
|
||||||
|
int outOff) {
|
||||||
|
outBytes[outOff] = (byte) word;
|
||||||
|
outBytes[outOff + 1] = (byte) ((uint) word >> 8);
|
||||||
|
outBytes[outOff + 2] = (byte) ((uint) word >> 16);
|
||||||
|
outBytes[outOff + 3] = (byte) ((uint) word >> 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override int DoFinal(
|
||||||
|
byte[] output,
|
||||||
|
int outOff) {
|
||||||
|
Finish();
|
||||||
|
|
||||||
|
UnpackWord(H1, output, outOff);
|
||||||
|
UnpackWord(H2, output, outOff + 4);
|
||||||
|
UnpackWord(H3, output, outOff + 8);
|
||||||
|
UnpackWord(H4, output, outOff + 12);
|
||||||
|
|
||||||
|
Reset();
|
||||||
|
|
||||||
|
return DigestLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* reset the chaining variables to the IV values.
|
||||||
|
*/
|
||||||
|
|
||||||
|
public override void Reset() {
|
||||||
|
base.Reset();
|
||||||
|
|
||||||
|
H1 = unchecked(0x67452301);
|
||||||
|
H2 = unchecked((int) 0xefcdab89);
|
||||||
|
H3 = unchecked((int) 0x98badcfe);
|
||||||
|
H4 = unchecked(0x10325476);
|
||||||
|
|
||||||
|
xOff = 0;
|
||||||
|
|
||||||
|
for (int i = 0; i != X.Length; i++) {
|
||||||
|
X[i] = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* rotate int x left n bits.
|
||||||
|
*/
|
||||||
|
|
||||||
|
private int RotateLeft(
|
||||||
|
int x,
|
||||||
|
int n) {
|
||||||
|
return (x << n) | (int) ((uint) x >> (32 - n));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* F, G, H and I are the basic MD5 functions.
|
||||||
|
*/
|
||||||
|
|
||||||
|
private int F(
|
||||||
|
int u,
|
||||||
|
int v,
|
||||||
|
int w) {
|
||||||
|
return (u & v) | (~u & w);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int G(
|
||||||
|
int u,
|
||||||
|
int v,
|
||||||
|
int w) {
|
||||||
|
return (u & w) | (v & ~w);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int H(
|
||||||
|
int u,
|
||||||
|
int v,
|
||||||
|
int w) {
|
||||||
|
return u ^ v ^ w;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int K(
|
||||||
|
int u,
|
||||||
|
int v,
|
||||||
|
int w) {
|
||||||
|
return v ^ (u | ~w);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal override void ProcessBlock() {
|
||||||
|
int a = H1;
|
||||||
|
int b = H2;
|
||||||
|
int c = H3;
|
||||||
|
int d = H4;
|
||||||
|
|
||||||
|
//
|
||||||
|
// Round 1 - F cycle, 16 times.
|
||||||
|
//
|
||||||
|
a = RotateLeft((a + F(b, c, d) + X[0] + unchecked((int) 0xd76aa478)), S11) + b;
|
||||||
|
d = RotateLeft((d + F(a, b, c) + X[1] + unchecked((int) 0xe8c7b756)), S12) + a;
|
||||||
|
c = RotateLeft((c + F(d, a, b) + X[2] + unchecked(0x242070db)), S13) + d;
|
||||||
|
b = RotateLeft((b + F(c, d, a) + X[3] + unchecked((int) 0xc1bdceee)), S14) + c;
|
||||||
|
a = RotateLeft((a + F(b, c, d) + X[4] + unchecked((int) 0xf57c0faf)), S11) + b;
|
||||||
|
d = RotateLeft((d + F(a, b, c) + X[5] + unchecked(0x4787c62a)), S12) + a;
|
||||||
|
c = RotateLeft((c + F(d, a, b) + X[6] + unchecked((int) 0xa8304613)), S13) + d;
|
||||||
|
b = RotateLeft((b + F(c, d, a) + X[7] + unchecked((int) 0xfd469501)), S14) + c;
|
||||||
|
a = RotateLeft((a + F(b, c, d) + X[8] + unchecked(0x698098d8)), S11) + b;
|
||||||
|
d = RotateLeft((d + F(a, b, c) + X[9] + unchecked((int) 0x8b44f7af)), S12) + a;
|
||||||
|
c = RotateLeft((c + F(d, a, b) + X[10] + unchecked((int) 0xffff5bb1)), S13) + d;
|
||||||
|
b = RotateLeft((b + F(c, d, a) + X[11] + unchecked((int) 0x895cd7be)), S14) + c;
|
||||||
|
a = RotateLeft((a + F(b, c, d) + X[12] + unchecked(0x6b901122)), S11) + b;
|
||||||
|
d = RotateLeft((d + F(a, b, c) + X[13] + unchecked((int) 0xfd987193)), S12) + a;
|
||||||
|
c = RotateLeft((c + F(d, a, b) + X[14] + unchecked((int) 0xa679438e)), S13) + d;
|
||||||
|
b = RotateLeft((b + F(c, d, a) + X[15] + unchecked(0x49b40821)), S14) + c;
|
||||||
|
|
||||||
|
//
|
||||||
|
// Round 2 - G cycle, 16 times.
|
||||||
|
//
|
||||||
|
a = RotateLeft((a + G(b, c, d) + X[1] + unchecked((int) 0xf61e2562)), S21) + b;
|
||||||
|
d = RotateLeft((d + G(a, b, c) + X[6] + unchecked((int) 0xc040b340)), S22) + a;
|
||||||
|
c = RotateLeft((c + G(d, a, b) + X[11] + unchecked(0x265e5a51)), S23) + d;
|
||||||
|
b = RotateLeft((b + G(c, d, a) + X[0] + unchecked((int) 0xe9b6c7aa)), S24) + c;
|
||||||
|
a = RotateLeft((a + G(b, c, d) + X[5] + unchecked((int) 0xd62f105d)), S21) + b;
|
||||||
|
d = RotateLeft((d + G(a, b, c) + X[10] + unchecked(0x02441453)), S22) + a;
|
||||||
|
c = RotateLeft((c + G(d, a, b) + X[15] + unchecked((int) 0xd8a1e681)), S23) + d;
|
||||||
|
b = RotateLeft((b + G(c, d, a) + X[4] + unchecked((int) 0xe7d3fbc8)), S24) + c;
|
||||||
|
a = RotateLeft((a + G(b, c, d) + X[9] + unchecked(0x21e1cde6)), S21) + b;
|
||||||
|
d = RotateLeft((d + G(a, b, c) + X[14] + unchecked((int) 0xc33707d6)), S22) + a;
|
||||||
|
c = RotateLeft((c + G(d, a, b) + X[3] + unchecked((int) 0xf4d50d87)), S23) + d;
|
||||||
|
b = RotateLeft((b + G(c, d, a) + X[8] + unchecked(0x455a14ed)), S24) + c;
|
||||||
|
a = RotateLeft((a + G(b, c, d) + X[13] + unchecked((int) 0xa9e3e905)), S21) + b;
|
||||||
|
d = RotateLeft((d + G(a, b, c) + X[2] + unchecked((int) 0xfcefa3f8)), S22) + a;
|
||||||
|
c = RotateLeft((c + G(d, a, b) + X[7] + unchecked(0x676f02d9)), S23) + d;
|
||||||
|
b = RotateLeft((b + G(c, d, a) + X[12] + unchecked((int) 0x8d2a4c8a)), S24) + c;
|
||||||
|
|
||||||
|
//
|
||||||
|
// Round 3 - H cycle, 16 times.
|
||||||
|
//
|
||||||
|
a = RotateLeft((a + H(b, c, d) + X[5] + unchecked((int) 0xfffa3942)), S31) + b;
|
||||||
|
d = RotateLeft((d + H(a, b, c) + X[8] + unchecked((int) 0x8771f681)), S32) + a;
|
||||||
|
c = RotateLeft((c + H(d, a, b) + X[11] + unchecked(0x6d9d6122)), S33) + d;
|
||||||
|
b = RotateLeft((b + H(c, d, a) + X[14] + unchecked((int) 0xfde5380c)), S34) + c;
|
||||||
|
a = RotateLeft((a + H(b, c, d) + X[1] + unchecked((int) 0xa4beea44)), S31) + b;
|
||||||
|
d = RotateLeft((d + H(a, b, c) + X[4] + unchecked(0x4bdecfa9)), S32) + a;
|
||||||
|
c = RotateLeft((c + H(d, a, b) + X[7] + unchecked((int) 0xf6bb4b60)), S33) + d;
|
||||||
|
b = RotateLeft((b + H(c, d, a) + X[10] + unchecked((int) 0xbebfbc70)), S34) + c;
|
||||||
|
a = RotateLeft((a + H(b, c, d) + X[13] + unchecked(0x289b7ec6)), S31) + b;
|
||||||
|
d = RotateLeft((d + H(a, b, c) + X[0] + unchecked((int) 0xeaa127fa)), S32) + a;
|
||||||
|
c = RotateLeft((c + H(d, a, b) + X[3] + unchecked((int) 0xd4ef3085)), S33) + d;
|
||||||
|
b = RotateLeft((b + H(c, d, a) + X[6] + unchecked(0x04881d05)), S34) + c;
|
||||||
|
a = RotateLeft((a + H(b, c, d) + X[9] + unchecked((int) 0xd9d4d039)), S31) + b;
|
||||||
|
d = RotateLeft((d + H(a, b, c) + X[12] + unchecked((int) 0xe6db99e5)), S32) + a;
|
||||||
|
c = RotateLeft((c + H(d, a, b) + X[15] + unchecked(0x1fa27cf8)), S33) + d;
|
||||||
|
b = RotateLeft((b + H(c, d, a) + X[2] + unchecked((int) 0xc4ac5665)), S34) + c;
|
||||||
|
|
||||||
|
//
|
||||||
|
// Round 4 - K cycle, 16 times.
|
||||||
|
//
|
||||||
|
a = RotateLeft((a + K(b, c, d) + X[0] + unchecked((int) 0xf4292244)), S41) + b;
|
||||||
|
d = RotateLeft((d + K(a, b, c) + X[7] + unchecked(0x432aff97)), S42) + a;
|
||||||
|
c = RotateLeft((c + K(d, a, b) + X[14] + unchecked((int) 0xab9423a7)), S43) + d;
|
||||||
|
b = RotateLeft((b + K(c, d, a) + X[5] + unchecked((int) 0xfc93a039)), S44) + c;
|
||||||
|
a = RotateLeft((a + K(b, c, d) + X[12] + unchecked(0x655b59c3)), S41) + b;
|
||||||
|
d = RotateLeft((d + K(a, b, c) + X[3] + unchecked((int) 0x8f0ccc92)), S42) + a;
|
||||||
|
c = RotateLeft((c + K(d, a, b) + X[10] + unchecked((int) 0xffeff47d)), S43) + d;
|
||||||
|
b = RotateLeft((b + K(c, d, a) + X[1] + unchecked((int) 0x85845dd1)), S44) + c;
|
||||||
|
a = RotateLeft((a + K(b, c, d) + X[8] + unchecked(0x6fa87e4f)), S41) + b;
|
||||||
|
d = RotateLeft((d + K(a, b, c) + X[15] + unchecked((int) 0xfe2ce6e0)), S42) + a;
|
||||||
|
c = RotateLeft((c + K(d, a, b) + X[6] + unchecked((int) 0xa3014314)), S43) + d;
|
||||||
|
b = RotateLeft((b + K(c, d, a) + X[13] + unchecked(0x4e0811a1)), S44) + c;
|
||||||
|
a = RotateLeft((a + K(b, c, d) + X[4] + unchecked((int) 0xf7537e82)), S41) + b;
|
||||||
|
d = RotateLeft((d + K(a, b, c) + X[11] + unchecked((int) 0xbd3af235)), S42) + a;
|
||||||
|
c = RotateLeft((c + K(d, a, b) + X[2] + unchecked(0x2ad7d2bb)), S43) + d;
|
||||||
|
b = RotateLeft((b + K(c, d, a) + X[9] + unchecked((int) 0xeb86d391)), S44) + c;
|
||||||
|
|
||||||
|
H1 += a;
|
||||||
|
H2 += b;
|
||||||
|
H3 += c;
|
||||||
|
H4 += d;
|
||||||
|
|
||||||
|
//
|
||||||
|
// reset the offset and clean out the word buffer.
|
||||||
|
//
|
||||||
|
xOff = 0;
|
||||||
|
for (int i = 0; i != X.Length; i++) {
|
||||||
|
X[i] = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
70
TLSharp.Core/MTProto/Crypto/RSA.cs
Normal file
70
TLSharp.Core/MTProto/Crypto/RSA.cs
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.MTProto.Crypto {
|
||||||
|
|
||||||
|
class RSAServerKey {
|
||||||
|
|
||||||
|
private string fingerprint;
|
||||||
|
private BigInteger m;
|
||||||
|
private BigInteger e;
|
||||||
|
|
||||||
|
public RSAServerKey(string fingerprint, BigInteger m, BigInteger e) {
|
||||||
|
this.fingerprint = fingerprint;
|
||||||
|
this.m = m;
|
||||||
|
this.e = e;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] Encrypt(byte[] data, int offset, int length) {
|
||||||
|
|
||||||
|
using(MemoryStream buffer = new MemoryStream(255))
|
||||||
|
using(BinaryWriter writer = new BinaryWriter(buffer)) {
|
||||||
|
using(SHA1 sha1 = new SHA1Managed()) {
|
||||||
|
byte[] hashsum = sha1.ComputeHash(data, offset, length);
|
||||||
|
writer.Write(hashsum);
|
||||||
|
}
|
||||||
|
|
||||||
|
buffer.Write(data, offset, length);
|
||||||
|
if(length < 235) {
|
||||||
|
byte[] padding = new byte[235 - length];
|
||||||
|
new Random().NextBytes(padding);
|
||||||
|
buffer.Write(padding, 0, padding.Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] ciphertext = new BigInteger(1, buffer.ToArray()).ModPow(e, m).ToByteArrayUnsigned();
|
||||||
|
|
||||||
|
if(ciphertext.Length == 256) {
|
||||||
|
return ciphertext;
|
||||||
|
} else {
|
||||||
|
byte[] paddedCiphertext = new byte[256];
|
||||||
|
int padding = 256 - ciphertext.Length;
|
||||||
|
for(int i = 0; i < padding; i++) {
|
||||||
|
paddedCiphertext[i] = 0;
|
||||||
|
}
|
||||||
|
ciphertext.CopyTo(paddedCiphertext, padding);
|
||||||
|
return paddedCiphertext;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public class RSA {
|
||||||
|
private static readonly Dictionary<string, RSAServerKey> serverKeys = new Dictionary<string, RSAServerKey>() {
|
||||||
|
{ "216be86c022bb4c3", new RSAServerKey("216be86c022bb4c3", new BigInteger("00C150023E2F70DB7985DED064759CFECF0AF328E69A41DAF4D6F01B538135A6F91F8F8B2A0EC9BA9720CE352EFCF6C5680FFC424BD634864902DE0B4BD6D49F4E580230E3AE97D95C8B19442B3C0A10D8F5633FECEDD6926A7F6DAB0DDB7D457F9EA81B8465FCD6FFFEED114011DF91C059CAEDAF97625F6C96ECC74725556934EF781D866B34F011FCE4D835A090196E9A5F0E4449AF7EB697DDB9076494CA5F81104A305B6DD27665722C46B60E5DF680FB16B210607EF217652E60236C255F6A28315F4083A96791D7214BF64C1DF4FD0DB1944FB26A2A57031B32EEE64AD15A8BA68885CDE74A5BFC920F6ABF59BA5C75506373E7130F9042DA922179251F", 16), new BigInteger("010001", 16)) }
|
||||||
|
};
|
||||||
|
|
||||||
|
public static byte[] Encrypt(string fingerprint, byte[] data, int offset, int length) {
|
||||||
|
string fingerprintLower = fingerprint.ToLower();
|
||||||
|
if(!serverKeys.ContainsKey(fingerprintLower)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
RSAServerKey key = serverKeys[fingerprintLower];
|
||||||
|
|
||||||
|
return key.Encrypt(data, offset, length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
77
TLSharp.Core/MTProto/Crypto/Salt.cs
Normal file
77
TLSharp.Core/MTProto/Crypto/Salt.cs
Normal file
|
|
@ -0,0 +1,77 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.MTProto.Crypto {
|
||||||
|
public class Salt : IComparable<Salt> {
|
||||||
|
private int validSince;
|
||||||
|
private int validUntil;
|
||||||
|
private ulong salt;
|
||||||
|
|
||||||
|
public Salt(int validSince, int validUntil, ulong salt) {
|
||||||
|
this.validSince = validSince;
|
||||||
|
this.validUntil = validUntil;
|
||||||
|
this.salt = salt;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int ValidSince {
|
||||||
|
get { return validSince; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public int ValidUntil {
|
||||||
|
get { return validUntil; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public ulong Value {
|
||||||
|
get { return salt; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public int CompareTo(Salt other) {
|
||||||
|
return validUntil.CompareTo(other.validSince);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class SaltCollection {
|
||||||
|
private SortedSet<Salt> salts;
|
||||||
|
|
||||||
|
public void Add(Salt salt) {
|
||||||
|
salts.Add(salt);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int Count {
|
||||||
|
get {
|
||||||
|
return salts.Count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// TODO: get actual salt and other...
|
||||||
|
}
|
||||||
|
|
||||||
|
public class GetFutureSaltsResponse {
|
||||||
|
private ulong requestId;
|
||||||
|
private int now;
|
||||||
|
private SaltCollection salts;
|
||||||
|
|
||||||
|
public GetFutureSaltsResponse(ulong requestId, int now) {
|
||||||
|
this.requestId = requestId;
|
||||||
|
this.now = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void AddSalt(Salt salt) {
|
||||||
|
salts.Add(salt);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ulong RequestId {
|
||||||
|
get { return requestId; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public int Now {
|
||||||
|
get { return now; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public SaltCollection Salts {
|
||||||
|
get { return salts; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
81
TLSharp.Core/MTProto/Serializers.cs
Normal file
81
TLSharp.Core/MTProto/Serializers.cs
Normal file
|
|
@ -0,0 +1,81 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.MTProto
|
||||||
|
{
|
||||||
|
public class Serializers {
|
||||||
|
|
||||||
|
public static class Bytes {
|
||||||
|
public static byte[] read(BinaryReader binaryReader) {
|
||||||
|
byte firstByte = binaryReader.ReadByte();
|
||||||
|
int len, padding;
|
||||||
|
if(firstByte == 254) {
|
||||||
|
len = binaryReader.ReadByte() | (binaryReader.ReadByte() << 8) | (binaryReader.ReadByte() << 16);
|
||||||
|
padding = len%4;
|
||||||
|
} else {
|
||||||
|
len = firstByte;
|
||||||
|
padding = (len + 1) % 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] data = binaryReader.ReadBytes(len);
|
||||||
|
if(padding > 0) {
|
||||||
|
padding = 4 - padding;
|
||||||
|
binaryReader.ReadBytes(padding);
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BinaryWriter write(BinaryWriter binaryWriter, byte[] data) {
|
||||||
|
int padding;
|
||||||
|
if(data.Length < 254) {
|
||||||
|
padding = (data.Length + 1)%4;
|
||||||
|
if(padding != 0) {
|
||||||
|
padding = 4 - padding;
|
||||||
|
}
|
||||||
|
|
||||||
|
binaryWriter.Write((byte) data.Length);
|
||||||
|
binaryWriter.Write(data);
|
||||||
|
} else {
|
||||||
|
padding = (data.Length)%4;
|
||||||
|
if(padding != 0) {
|
||||||
|
padding = 4 - padding;
|
||||||
|
}
|
||||||
|
|
||||||
|
binaryWriter.Write((byte)254);
|
||||||
|
binaryWriter.Write((byte)(data.Length));
|
||||||
|
binaryWriter.Write((byte)(data.Length >> 8));
|
||||||
|
binaryWriter.Write((byte)(data.Length >> 16));
|
||||||
|
binaryWriter.Write(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
for(int i = 0; i < padding; i++) {
|
||||||
|
binaryWriter.Write((byte)0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return binaryWriter;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class String {
|
||||||
|
public static string read(BinaryReader reader) {
|
||||||
|
byte[] data = Bytes.read(reader);
|
||||||
|
return Encoding.UTF8.GetString(data, 0, data.Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BinaryWriter write(BinaryWriter writer, string str) {
|
||||||
|
return Bytes.write(writer, Encoding.UTF8.GetBytes(str));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string VectorToString<T>(List<T> list) {
|
||||||
|
string[] tokens = new string[list.Count];
|
||||||
|
for(int i = 0; i < list.Count; i++) {
|
||||||
|
tokens[i] = list[i].ToString();
|
||||||
|
}
|
||||||
|
return "[" + System.String.Join(", ", tokens) + "]";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
14822
TLSharp.Core/MTProto/TL.cs
Normal file
14822
TLSharp.Core/MTProto/TL.cs
Normal file
File diff suppressed because it is too large
Load diff
77
TLSharp.Core/Network/MtProtoPlainSender.cs
Normal file
77
TLSharp.Core/Network/MtProtoPlainSender.cs
Normal file
|
|
@ -0,0 +1,77 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.Network
|
||||||
|
{
|
||||||
|
public class MtProtoPlainSender
|
||||||
|
{
|
||||||
|
private int sequence = 0;
|
||||||
|
private int timeOffset;
|
||||||
|
private long lastMessageId;
|
||||||
|
private Random random;
|
||||||
|
private TcpTransport _transport;
|
||||||
|
|
||||||
|
public MtProtoPlainSender(TcpTransport transport)
|
||||||
|
{
|
||||||
|
_transport = transport;
|
||||||
|
random = new Random();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Send(byte[] data)
|
||||||
|
{
|
||||||
|
using (var memoryStream = new MemoryStream())
|
||||||
|
{
|
||||||
|
using (var binaryWriter = new BinaryWriter(memoryStream))
|
||||||
|
{
|
||||||
|
binaryWriter.Write((long)0);
|
||||||
|
binaryWriter.Write(GetNewMessageId());
|
||||||
|
binaryWriter.Write(data.Length);
|
||||||
|
binaryWriter.Write(data);
|
||||||
|
|
||||||
|
byte[] packet = memoryStream.ToArray();
|
||||||
|
|
||||||
|
await _transport.Send(packet);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<byte[]> Recieve()
|
||||||
|
{
|
||||||
|
var result = await _transport.Receieve();
|
||||||
|
|
||||||
|
using (var memoryStream = new MemoryStream(result.Body))
|
||||||
|
{
|
||||||
|
using (BinaryReader binaryReader = new BinaryReader(memoryStream))
|
||||||
|
{
|
||||||
|
long authKeyid = binaryReader.ReadInt64();
|
||||||
|
long messageId = binaryReader.ReadInt64();
|
||||||
|
int messageLength = binaryReader.ReadInt32();
|
||||||
|
|
||||||
|
byte[] response = binaryReader.ReadBytes(messageLength);
|
||||||
|
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private long GetNewMessageId()
|
||||||
|
{
|
||||||
|
long time = Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds);
|
||||||
|
long newMessageId = ((time / 1000 + timeOffset) << 32) |
|
||||||
|
((time % 1000) << 22) |
|
||||||
|
(random.Next(524288) << 2); // 2^19
|
||||||
|
// [ unix timestamp : 32 bit] [ milliseconds : 10 bit ] [ buffer space : 1 bit ] [ random : 19 bit ] [ msg_id type : 2 bit ] = [ msg_id : 64 bit ]
|
||||||
|
|
||||||
|
if (lastMessageId >= newMessageId)
|
||||||
|
{
|
||||||
|
newMessageId = lastMessageId + 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
lastMessageId = newMessageId;
|
||||||
|
return newMessageId;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
458
TLSharp.Core/Network/MtProtoSender.cs
Normal file
458
TLSharp.Core/Network/MtProtoSender.cs
Normal file
|
|
@ -0,0 +1,458 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Ionic.Zlib;
|
||||||
|
using TLSharp.Core.MTProto;
|
||||||
|
using TLSharp.Core.MTProto.Crypto;
|
||||||
|
using TLSharp.Core.Requests;
|
||||||
|
using TLSharp.Core.Utils;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.Network
|
||||||
|
{
|
||||||
|
public class MtProtoSender
|
||||||
|
{
|
||||||
|
//private ulong sessionId = GenerateRandomUlong();
|
||||||
|
|
||||||
|
private TcpTransport _transport;
|
||||||
|
private Session _session;
|
||||||
|
|
||||||
|
public List<ulong> needConfirmation = new List<ulong>();
|
||||||
|
|
||||||
|
public MtProtoSender(TcpTransport transport, Session session)
|
||||||
|
{
|
||||||
|
_transport = transport;
|
||||||
|
_session = session;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int GenerateSequence(bool confirmed)
|
||||||
|
{
|
||||||
|
return confirmed ? _session.Sequence++ * 2 + 1 : _session.Sequence * 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Send(MTProtoRequest request)
|
||||||
|
{
|
||||||
|
// TODO: refactor
|
||||||
|
if (needConfirmation.Any())
|
||||||
|
{
|
||||||
|
var ackRequest = new AckRequest(needConfirmation);
|
||||||
|
using (var memory = new MemoryStream())
|
||||||
|
using (var writer = new BinaryWriter(memory))
|
||||||
|
{
|
||||||
|
ackRequest.OnSend(writer);
|
||||||
|
await Send(memory.ToArray(), ackRequest);
|
||||||
|
needConfirmation.Clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
using (var memory = new MemoryStream())
|
||||||
|
using (var writer = new BinaryWriter(memory))
|
||||||
|
{
|
||||||
|
request.OnSend(writer);
|
||||||
|
await Send(memory.ToArray(), request);
|
||||||
|
}
|
||||||
|
|
||||||
|
_session.Save();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Send(byte[] packet, MTProtoRequest request)
|
||||||
|
{
|
||||||
|
request.MessageId = _session.GetNewMessageId();
|
||||||
|
|
||||||
|
byte[] msgKey;
|
||||||
|
byte[] ciphertext;
|
||||||
|
using (MemoryStream plaintextPacket = makeMemory(8 + 8 + 8 + 4 + 4 + packet.Length))
|
||||||
|
{
|
||||||
|
using (BinaryWriter plaintextWriter = new BinaryWriter(plaintextPacket))
|
||||||
|
{
|
||||||
|
plaintextWriter.Write(_session.Salt);
|
||||||
|
plaintextWriter.Write(_session.Id);
|
||||||
|
plaintextWriter.Write(request.MessageId);
|
||||||
|
plaintextWriter.Write(GenerateSequence(request.Confirmed));
|
||||||
|
plaintextWriter.Write(packet.Length);
|
||||||
|
plaintextWriter.Write(packet);
|
||||||
|
|
||||||
|
msgKey = Helpers.CalcMsgKey(plaintextPacket.GetBuffer());
|
||||||
|
ciphertext = AES.EncryptAES(Helpers.CalcKey(_session.AuthKey.Data, msgKey, true), plaintextPacket.GetBuffer());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
using (MemoryStream ciphertextPacket = makeMemory(8 + 16 + ciphertext.Length))
|
||||||
|
{
|
||||||
|
using (BinaryWriter writer = new BinaryWriter(ciphertextPacket))
|
||||||
|
{
|
||||||
|
writer.Write(_session.AuthKey.Id);
|
||||||
|
writer.Write(msgKey);
|
||||||
|
writer.Write(ciphertext);
|
||||||
|
|
||||||
|
await _transport.Send(ciphertextPacket.GetBuffer());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Tuple<byte[], ulong, int> DecodeMessage(byte[] body)
|
||||||
|
{
|
||||||
|
byte[] message;
|
||||||
|
ulong remoteMessageId;
|
||||||
|
int remoteSequence;
|
||||||
|
|
||||||
|
using (MemoryStream inputStream = new MemoryStream(body))
|
||||||
|
using (BinaryReader inputReader = new BinaryReader(inputStream))
|
||||||
|
{
|
||||||
|
ulong remoteAuthKeyId = inputReader.ReadUInt64(); // TODO: check auth key id
|
||||||
|
byte[] msgKey = inputReader.ReadBytes(16); // TODO: check msg_key correctness
|
||||||
|
AESKeyData keyData = Helpers.CalcKey(_session.AuthKey.Data, msgKey, false);
|
||||||
|
|
||||||
|
byte[] plaintext = AES.DecryptAES(keyData, inputReader.ReadBytes((int)(inputStream.Length - inputStream.Position)));
|
||||||
|
|
||||||
|
using (MemoryStream plaintextStream = new MemoryStream(plaintext))
|
||||||
|
using (BinaryReader plaintextReader = new BinaryReader(plaintextStream))
|
||||||
|
{
|
||||||
|
var remoteSalt = plaintextReader.ReadUInt64();
|
||||||
|
var remoteSessionId = plaintextReader.ReadUInt64();
|
||||||
|
remoteMessageId = plaintextReader.ReadUInt64();
|
||||||
|
remoteSequence = plaintextReader.ReadInt32();
|
||||||
|
int msgLen = plaintextReader.ReadInt32();
|
||||||
|
message = plaintextReader.ReadBytes(msgLen);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Tuple<byte[], ulong, int>(message, remoteMessageId, remoteSequence);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<byte[]> Recieve(MTProtoRequest request)
|
||||||
|
{
|
||||||
|
while (!request.ConfirmReceived)
|
||||||
|
{
|
||||||
|
var result = DecodeMessage((await _transport.Receieve()).Body);
|
||||||
|
|
||||||
|
using (MemoryStream messageStream = new MemoryStream(result.Item1, false))
|
||||||
|
using (BinaryReader messageReader = new BinaryReader(messageStream))
|
||||||
|
{
|
||||||
|
processMessage(result.Item2, result.Item3, messageReader, request);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool processMessage(ulong messageId, int sequence, BinaryReader messageReader, MTProtoRequest request)
|
||||||
|
{
|
||||||
|
// TODO: check salt
|
||||||
|
// TODO: check sessionid
|
||||||
|
// TODO: check seqno
|
||||||
|
|
||||||
|
//logger.debug("processMessage: msg_id {0}, sequence {1}, data {2}", BitConverter.ToString(((MemoryStream)messageReader.BaseStream).GetBuffer(), (int) messageReader.BaseStream.Position, (int) (messageReader.BaseStream.Length - messageReader.BaseStream.Position)).Replace("-","").ToLower());
|
||||||
|
needConfirmation.Add(messageId);
|
||||||
|
|
||||||
|
uint code = messageReader.ReadUInt32();
|
||||||
|
messageReader.BaseStream.Position -= 4;
|
||||||
|
switch (code)
|
||||||
|
{
|
||||||
|
case 0x73f1f8dc: // container
|
||||||
|
//logger.debug("MSG container");
|
||||||
|
return HandleContainer(messageId, sequence, messageReader, request);
|
||||||
|
case 0x7abe77ec: // ping
|
||||||
|
//logger.debug("MSG ping");
|
||||||
|
return HandlePing(messageId, sequence, messageReader);
|
||||||
|
case 0x347773c5: // pong
|
||||||
|
//logger.debug("MSG pong");
|
||||||
|
return HandlePong(messageId, sequence, messageReader);
|
||||||
|
case 0xae500895: // future_salts
|
||||||
|
//logger.debug("MSG future_salts");
|
||||||
|
return HandleFutureSalts(messageId, sequence, messageReader);
|
||||||
|
case 0x9ec20908: // new_session_created
|
||||||
|
//logger.debug("MSG new_session_created");
|
||||||
|
return HandleNewSessionCreated(messageId, sequence, messageReader);
|
||||||
|
case 0x62d6b459: // msgs_ack
|
||||||
|
//logger.debug("MSG msds_ack");
|
||||||
|
return HandleMsgsAck(messageId, sequence, messageReader);
|
||||||
|
case 0xedab447b: // bad_server_salt
|
||||||
|
//logger.debug("MSG bad_server_salt");
|
||||||
|
return HandleBadServerSalt(messageId, sequence, messageReader, request);
|
||||||
|
case 0xa7eff811: // bad_msg_notification
|
||||||
|
//logger.debug("MSG bad_msg_notification");
|
||||||
|
return HandleBadMsgNotification(messageId, sequence, messageReader);
|
||||||
|
case 0x276d3ec6: // msg_detailed_info
|
||||||
|
//logger.debug("MSG msg_detailed_info");
|
||||||
|
return HandleMsgDetailedInfo(messageId, sequence, messageReader);
|
||||||
|
case 0xf35c6d01: // rpc_result
|
||||||
|
//logger.debug("MSG rpc_result");
|
||||||
|
return HandleRpcResult(messageId, sequence, messageReader, request);
|
||||||
|
case 0x3072cfa1: // gzip_packed
|
||||||
|
//logger.debug("MSG gzip_packed");
|
||||||
|
return HandleGzipPacked(messageId, sequence, messageReader, request);
|
||||||
|
case 0xe317af7e:
|
||||||
|
case 0xd3f45784:
|
||||||
|
case 0x2b2fbd4e:
|
||||||
|
case 0x78d4dec1:
|
||||||
|
case 0x725b04c3:
|
||||||
|
case 0x74ae4240:
|
||||||
|
return HandleUpdate(messageId, sequence, messageReader);
|
||||||
|
default:
|
||||||
|
//logger.debug("unknown message: {0}", code);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool HandleUpdate(ulong messageId, int sequence, BinaryReader messageReader)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
|
||||||
|
/*
|
||||||
|
try
|
||||||
|
{
|
||||||
|
UpdatesEvent(TL.Parse<Updates>(messageReader));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
logger.warning("update processing exception: {0}", e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool HandleGzipPacked(ulong messageId, int sequence, BinaryReader messageReader, MTProtoRequest request)
|
||||||
|
{
|
||||||
|
uint code = messageReader.ReadUInt32();
|
||||||
|
byte[] packedData = GZipStream.UncompressBuffer(Serializers.Bytes.read(messageReader));
|
||||||
|
using (MemoryStream packedStream = new MemoryStream(packedData, false))
|
||||||
|
using (BinaryReader compressedReader = new BinaryReader(packedStream))
|
||||||
|
{
|
||||||
|
processMessage(messageId, sequence, compressedReader, request);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool HandleRpcResult(ulong messageId, int sequence, BinaryReader messageReader, MTProtoRequest request)
|
||||||
|
{
|
||||||
|
uint code = messageReader.ReadUInt32();
|
||||||
|
ulong requestId = messageReader.ReadUInt64();
|
||||||
|
|
||||||
|
if (requestId == (ulong) request.MessageId)
|
||||||
|
request.ConfirmReceived = true;
|
||||||
|
|
||||||
|
//throw new NotImplementedException();
|
||||||
|
/*
|
||||||
|
lock (runningRequests)
|
||||||
|
{
|
||||||
|
if (!runningRequests.ContainsKey(requestId))
|
||||||
|
{
|
||||||
|
logger.warning("rpc response on unknown request: {0}", requestId);
|
||||||
|
messageReader.BaseStream.Position -= 12;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
request = runningRequests[requestId];
|
||||||
|
runningRequests.Remove(requestId);
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
uint innerCode = messageReader.ReadUInt32();
|
||||||
|
if (innerCode == 0x2144ca19)
|
||||||
|
{ // rpc_error
|
||||||
|
int errorCode = messageReader.ReadInt32();
|
||||||
|
string errorMessage = Serializers.String.read(messageReader);
|
||||||
|
|
||||||
|
if (errorMessage.StartsWith("FLOOD_WAIT_"))
|
||||||
|
{
|
||||||
|
var resultString = Regex.Match(errorMessage, @"\d+").Value;
|
||||||
|
var seconds = int.Parse(resultString);
|
||||||
|
Debug.WriteLine($"Should wait {seconds} sec.");
|
||||||
|
Thread.Sleep(1000*seconds);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException(errorMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
else if (innerCode == 0x3072cfa1)
|
||||||
|
{
|
||||||
|
// gzip_packed
|
||||||
|
byte[] packedData = Serializers.Bytes.read(messageReader);
|
||||||
|
using (MemoryStream packedStream = new MemoryStream(packedData, false))
|
||||||
|
using (GZipStream zipStream = new GZipStream(packedStream, CompressionMode.Decompress))
|
||||||
|
using (BinaryReader compressedReader = new BinaryReader(zipStream))
|
||||||
|
{
|
||||||
|
request.OnResponse(compressedReader);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
messageReader.BaseStream.Position -= 4;
|
||||||
|
|
||||||
|
request.OnResponse(messageReader);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool HandleMsgDetailedInfo(ulong messageId, int sequence, BinaryReader messageReader)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool HandleBadMsgNotification(ulong messageId, int sequence, BinaryReader messageReader)
|
||||||
|
{
|
||||||
|
uint code = messageReader.ReadUInt32();
|
||||||
|
ulong requestId = messageReader.ReadUInt64();
|
||||||
|
int requestSequence = messageReader.ReadInt32();
|
||||||
|
int errorCode = messageReader.ReadInt32();
|
||||||
|
|
||||||
|
switch (errorCode)
|
||||||
|
{
|
||||||
|
case 16:
|
||||||
|
throw new InvalidOperationException(" msg_id too low (most likely, client time is wrong; it would be worthwhile to synchronize it using msg_id notifications and re-send the original message with the “correct” msg_id or wrap it in a container with a new msg_id if the original message had waited too long on the client to be transmitted)");
|
||||||
|
case 17:
|
||||||
|
throw new InvalidOperationException(" msg_id too high (similar to the previous case, the client time has to be synchronized, and the message re-sent with the correct msg_id)");
|
||||||
|
case 18:
|
||||||
|
throw new InvalidOperationException("incorrect two lower order msg_id bits (the server expects client message msg_id to be divisible by 4)");
|
||||||
|
case 19:
|
||||||
|
throw new InvalidOperationException("container msg_id is the same as msg_id of a previously received message (this must never happen)");
|
||||||
|
case 20:
|
||||||
|
throw new InvalidOperationException("message too old, and it cannot be verified whether the server has received a message with this msg_id or not");
|
||||||
|
case 32:
|
||||||
|
throw new InvalidOperationException("msg_seqno too low (the server has already received a message with a lower msg_id but with either a higher or an equal and odd seqno)");
|
||||||
|
case 33:
|
||||||
|
throw new InvalidOperationException(" msg_seqno too high (similarly, there is a message with a higher msg_id but with either a lower or an equal and odd seqno)");
|
||||||
|
case 34:
|
||||||
|
throw new InvalidOperationException("an even msg_seqno expected (irrelevant message), but odd received");
|
||||||
|
case 35:
|
||||||
|
throw new InvalidOperationException("odd msg_seqno expected (relevant message), but even received");
|
||||||
|
case 48:
|
||||||
|
throw new InvalidOperationException("incorrect server salt (in this case, the bad_server_salt response is received with the correct salt, and the message is to be re-sent with it)");
|
||||||
|
case 64:
|
||||||
|
throw new InvalidOperationException("invalid container");
|
||||||
|
|
||||||
|
}
|
||||||
|
throw new NotImplementedException();
|
||||||
|
/*
|
||||||
|
logger.debug("bad_msg_notification: msgid {0}, seq {1}, errorcode {2}", requestId, requestSequence,
|
||||||
|
errorCode);
|
||||||
|
*/
|
||||||
|
/*
|
||||||
|
if (!runningRequests.ContainsKey(requestId))
|
||||||
|
{
|
||||||
|
logger.debug("bad msg notification on unknown request");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
//OnBrokenSessionEvent();
|
||||||
|
//MTProtoRequest request = runningRequests[requestId];
|
||||||
|
//request.OnException(new MTProtoBadMessageException(errorCode));
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool HandleBadServerSalt(ulong messageId, int sequence, BinaryReader messageReader, MTProtoRequest request)
|
||||||
|
{
|
||||||
|
uint code = messageReader.ReadUInt32();
|
||||||
|
ulong badMsgId = messageReader.ReadUInt64();
|
||||||
|
int badMsgSeqNo = messageReader.ReadInt32();
|
||||||
|
int errorCode = messageReader.ReadInt32();
|
||||||
|
ulong newSalt = messageReader.ReadUInt64();
|
||||||
|
|
||||||
|
//logger.debug("bad_server_salt: msgid {0}, seq {1}, errorcode {2}, newsalt {3}", badMsgId, badMsgSeqNo, errorCode, newSalt);
|
||||||
|
|
||||||
|
_session.Salt = newSalt;
|
||||||
|
|
||||||
|
//resend
|
||||||
|
Send(request);
|
||||||
|
/*
|
||||||
|
if(!runningRequests.ContainsKey(badMsgId)) {
|
||||||
|
logger.debug("bad server salt on unknown message");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
//MTProtoRequest request = runningRequests[badMsgId];
|
||||||
|
//request.OnException(new MTProtoBadServerSaltException(salt));
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool HandleMsgsAck(ulong messageId, int sequence, BinaryReader messageReader)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool HandleNewSessionCreated(ulong messageId, int sequence, BinaryReader messageReader)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool HandleFutureSalts(ulong messageId, int sequence, BinaryReader messageReader)
|
||||||
|
{
|
||||||
|
uint code = messageReader.ReadUInt32();
|
||||||
|
ulong requestId = messageReader.ReadUInt64();
|
||||||
|
|
||||||
|
messageReader.BaseStream.Position -= 12;
|
||||||
|
|
||||||
|
throw new NotImplementedException();
|
||||||
|
/*
|
||||||
|
if (!runningRequests.ContainsKey(requestId))
|
||||||
|
{
|
||||||
|
logger.info("future salts on unknown request");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
// MTProtoRequest request = runningRequests[requestId];
|
||||||
|
// runningRequests.Remove(requestId);
|
||||||
|
// request.OnResponse(messageReader);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool HandlePong(ulong messageId, int sequence, BinaryReader messageReader)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool HandlePing(ulong messageId, int sequence, BinaryReader messageReader)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool HandleContainer(ulong messageId, int sequence, BinaryReader messageReader, MTProtoRequest request)
|
||||||
|
{
|
||||||
|
uint code = messageReader.ReadUInt32();
|
||||||
|
int size = messageReader.ReadInt32();
|
||||||
|
for (int i = 0; i < size; i++)
|
||||||
|
{
|
||||||
|
ulong innerMessageId = messageReader.ReadUInt64();
|
||||||
|
int innerSequence = messageReader.ReadInt32();
|
||||||
|
int innerLength = messageReader.ReadInt32();
|
||||||
|
long beginPosition = messageReader.BaseStream.Position;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!processMessage(innerMessageId, sequence, messageReader, request))
|
||||||
|
{
|
||||||
|
messageReader.BaseStream.Position = beginPosition + innerLength;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
// logger.error("failed to process message in contailer: {0}", e);
|
||||||
|
messageReader.BaseStream.Position = beginPosition + innerLength;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private MemoryStream makeMemory(int len)
|
||||||
|
{
|
||||||
|
return new MemoryStream(new byte[len], 0, len, true, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
86
TLSharp.Core/Network/TcpMessage.cs
Normal file
86
TLSharp.Core/Network/TcpMessage.cs
Normal file
|
|
@ -0,0 +1,86 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using Ionic.Crc;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.Network
|
||||||
|
{
|
||||||
|
public class TcpMessage
|
||||||
|
{
|
||||||
|
public int SequneceNumber { get; private set; }
|
||||||
|
public byte[] Body { get; private set; }
|
||||||
|
|
||||||
|
public TcpMessage(int seqNumber, byte[] body)
|
||||||
|
{
|
||||||
|
if (body == null)
|
||||||
|
throw new ArgumentNullException(nameof(body));
|
||||||
|
|
||||||
|
SequneceNumber = seqNumber;
|
||||||
|
Body = body;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] Encode()
|
||||||
|
{
|
||||||
|
using (var memoryStream = new MemoryStream())
|
||||||
|
{
|
||||||
|
using (var binaryWriter = new BinaryWriter(memoryStream))
|
||||||
|
{
|
||||||
|
// https://core.telegram.org/mtproto#tcp-transport
|
||||||
|
/*
|
||||||
|
4 length bytes are added at the front
|
||||||
|
(to include the length, the sequence number, and CRC32; always divisible by 4)
|
||||||
|
and 4 bytes with the packet sequence number within this TCP connection
|
||||||
|
(the first packet sent is numbered 0, the next one 1, etc.),
|
||||||
|
and 4 CRC32 bytes at the end (length, sequence number, and payload together).
|
||||||
|
*/
|
||||||
|
binaryWriter.Write(Body.Length + 12);
|
||||||
|
binaryWriter.Write(SequneceNumber);
|
||||||
|
binaryWriter.Write(Body);
|
||||||
|
var crc32 = new CRC32();
|
||||||
|
crc32.SlurpBlock(memoryStream.GetBuffer(), 0, 8 + Body.Length);
|
||||||
|
binaryWriter.Write(crc32.Crc32Result);
|
||||||
|
|
||||||
|
var transportPacket = memoryStream.ToArray();
|
||||||
|
|
||||||
|
// Debug.WriteLine("Tcp packet #{0}\n{1}", SequneceNumber, BitConverter.ToString(transportPacket));
|
||||||
|
|
||||||
|
return transportPacket;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static TcpMessage Decode(byte[] body)
|
||||||
|
{
|
||||||
|
if (body == null)
|
||||||
|
throw new ArgumentNullException(nameof(body));
|
||||||
|
|
||||||
|
if (body.Length < 12)
|
||||||
|
throw new InvalidOperationException("Ops, wrong size of input packet");
|
||||||
|
|
||||||
|
using (var memoryStream = new MemoryStream(body))
|
||||||
|
{
|
||||||
|
using (var binaryReader = new BinaryReader(memoryStream))
|
||||||
|
{
|
||||||
|
var packetLength = binaryReader.ReadInt32();
|
||||||
|
|
||||||
|
if (packetLength < 12)
|
||||||
|
throw new InvalidOperationException(string.Format("invalid packet length: {0}", packetLength));
|
||||||
|
|
||||||
|
var seq = binaryReader.ReadInt32();
|
||||||
|
byte[] packet = binaryReader.ReadBytes(packetLength - 12);
|
||||||
|
var checksum = (int)binaryReader.ReadInt32();
|
||||||
|
|
||||||
|
var crc32 = new CRC32();
|
||||||
|
crc32.SlurpBlock(body, 0, packetLength - 4);
|
||||||
|
var validChecksum = crc32.Crc32Result;
|
||||||
|
|
||||||
|
if (checksum != validChecksum)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("invalid checksum! skip");
|
||||||
|
}
|
||||||
|
|
||||||
|
return new TcpMessage(seq, packet);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
51
TLSharp.Core/Network/TcpTransport.cs
Normal file
51
TLSharp.Core/Network/TcpTransport.cs
Normal file
|
|
@ -0,0 +1,51 @@
|
||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Sockets;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.Network
|
||||||
|
{
|
||||||
|
public class TcpTransport : IDisposable
|
||||||
|
{
|
||||||
|
private const string defaultConnectionAddress = "91.108.56.165";
|
||||||
|
private const int defaultConnectionPort = 443;
|
||||||
|
private readonly TcpClient _tcpClient;
|
||||||
|
private int sendCounter = 0;
|
||||||
|
|
||||||
|
public TcpTransport(string address = defaultConnectionAddress, int port = defaultConnectionPort)
|
||||||
|
{
|
||||||
|
_tcpClient = new TcpClient();
|
||||||
|
|
||||||
|
var ipAddress = IPAddress.Parse(address);
|
||||||
|
_tcpClient.Connect(ipAddress, port);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Send(byte[] packet)
|
||||||
|
{
|
||||||
|
if (!_tcpClient.Connected)
|
||||||
|
throw new InvalidOperationException("Client not connected to server.");
|
||||||
|
|
||||||
|
var tcpMessage = new TcpMessage(sendCounter, packet);
|
||||||
|
|
||||||
|
await _tcpClient.GetStream().WriteAsync(tcpMessage.Encode(), 0, tcpMessage.Encode().Length);
|
||||||
|
sendCounter++;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<TcpMessage> Receieve()
|
||||||
|
{
|
||||||
|
var buffer = new byte[_tcpClient.ReceiveBufferSize];
|
||||||
|
var availableBytes = await _tcpClient.GetStream().ReadAsync(buffer, 0, buffer.Length);
|
||||||
|
|
||||||
|
var result = buffer.Take(availableBytes).ToArray();
|
||||||
|
|
||||||
|
return TcpMessage.Decode(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
if (_tcpClient.Connected)
|
||||||
|
_tcpClient.Close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
36
TLSharp.Core/Properties/AssemblyInfo.cs
Normal file
36
TLSharp.Core/Properties/AssemblyInfo.cs
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
|
// General Information about an assembly is controlled through the following
|
||||||
|
// set of attributes. Change these attribute values to modify the information
|
||||||
|
// associated with an assembly.
|
||||||
|
[assembly: AssemblyTitle("TLSharp.Core")]
|
||||||
|
[assembly: AssemblyDescription("")]
|
||||||
|
[assembly: AssemblyConfiguration("")]
|
||||||
|
[assembly: AssemblyCompany("")]
|
||||||
|
[assembly: AssemblyProduct("TLSharp.Core")]
|
||||||
|
[assembly: AssemblyCopyright("Copyright © 2015")]
|
||||||
|
[assembly: AssemblyTrademark("")]
|
||||||
|
[assembly: AssemblyCulture("")]
|
||||||
|
|
||||||
|
// Setting ComVisible to false makes the types in this assembly not visible
|
||||||
|
// to COM components. If you need to access a type in this assembly from
|
||||||
|
// COM, set the ComVisible attribute to true on that type.
|
||||||
|
[assembly: ComVisible(false)]
|
||||||
|
|
||||||
|
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||||
|
[assembly: Guid("400d2544-1cc6-4d8a-a62c-2292d9947a16")]
|
||||||
|
|
||||||
|
// Version information for an assembly consists of the following four values:
|
||||||
|
//
|
||||||
|
// Major Version
|
||||||
|
// Minor Version
|
||||||
|
// Build Number
|
||||||
|
// Revision
|
||||||
|
//
|
||||||
|
// You can specify all the values or you can default the Build and Revision Numbers
|
||||||
|
// by using the '*' as shown below:
|
||||||
|
// [assembly: AssemblyVersion("1.0.*")]
|
||||||
|
[assembly: AssemblyVersion("1.0.0.0")]
|
||||||
|
[assembly: AssemblyFileVersion("1.0.0.0")]
|
||||||
39
TLSharp.Core/Requests/AckRequest.cs
Normal file
39
TLSharp.Core/Requests/AckRequest.cs
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.Requests
|
||||||
|
{
|
||||||
|
public class AckRequest : MTProtoRequest
|
||||||
|
{
|
||||||
|
private readonly List<ulong> _msgs;
|
||||||
|
public AckRequest(List<ulong> msgs)
|
||||||
|
{
|
||||||
|
_msgs = msgs;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnSend(BinaryWriter writer)
|
||||||
|
{
|
||||||
|
writer.Write(0x62d6b459); // msgs_ack
|
||||||
|
writer.Write(0x1cb5c415); // Vector
|
||||||
|
writer.Write(_msgs.Count);
|
||||||
|
foreach (ulong messageId in _msgs)
|
||||||
|
{
|
||||||
|
writer.Write(messageId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnResponse(BinaryReader reader)
|
||||||
|
{
|
||||||
|
//throw new NotImplementedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnException(Exception exception)
|
||||||
|
{
|
||||||
|
throw new NotImplementedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool Confirmed => false;
|
||||||
|
public override bool Responded { get; }
|
||||||
|
}
|
||||||
|
}
|
||||||
39
TLSharp.Core/Requests/AuthCheckPhoneRequest.cs
Normal file
39
TLSharp.Core/Requests/AuthCheckPhoneRequest.cs
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using TLSharp.Core.MTProto;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.Requests
|
||||||
|
{
|
||||||
|
public class AuthCheckPhoneRequest : MTProtoRequest
|
||||||
|
{
|
||||||
|
private string _phoneNumber;
|
||||||
|
public bool _phoneRegistered;
|
||||||
|
private bool _phoneInvited;
|
||||||
|
|
||||||
|
public AuthCheckPhoneRequest(string phoneNumber)
|
||||||
|
{
|
||||||
|
_phoneNumber = phoneNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnSend(BinaryWriter writer)
|
||||||
|
{
|
||||||
|
writer.Write(0x6fe51dfb);
|
||||||
|
Serializers.String.write(writer, _phoneNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnResponse(BinaryReader reader)
|
||||||
|
{
|
||||||
|
var dataCode = reader.ReadUInt32(); // #e300cc3b
|
||||||
|
this._phoneRegistered = reader.ReadUInt32() == 0x997275b5;
|
||||||
|
this._phoneInvited = reader.ReadUInt32() == 0x997275b5;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnException(Exception exception)
|
||||||
|
{
|
||||||
|
throw new NotImplementedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool Confirmed => true;
|
||||||
|
public override bool Responded { get; }
|
||||||
|
}
|
||||||
|
}
|
||||||
54
TLSharp.Core/Requests/AuthSendCodeRequest.cs
Normal file
54
TLSharp.Core/Requests/AuthSendCodeRequest.cs
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using TLSharp.Core.MTProto;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.Requests
|
||||||
|
{
|
||||||
|
public class AuthSendCodeRequest : MTProtoRequest
|
||||||
|
{
|
||||||
|
private readonly string _phoneNumber;
|
||||||
|
private readonly int _smsType;
|
||||||
|
private readonly int _apiId;
|
||||||
|
private readonly string _apiHash;
|
||||||
|
private readonly string _langCode;
|
||||||
|
public bool _phoneRegistered;
|
||||||
|
public string _phoneCodeHash;
|
||||||
|
|
||||||
|
public AuthSendCodeRequest(string phoneNumber, int smsType, int apiId, string apiHash, string langCode)
|
||||||
|
{
|
||||||
|
_phoneNumber = phoneNumber;
|
||||||
|
_smsType = smsType;
|
||||||
|
_apiId = apiId;
|
||||||
|
_apiHash = apiHash;
|
||||||
|
_langCode = langCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnSend(BinaryWriter writer)
|
||||||
|
{
|
||||||
|
writer.Write(0x768d5f4d);
|
||||||
|
Serializers.String.write(writer, _phoneNumber);
|
||||||
|
writer.Write(_smsType);
|
||||||
|
writer.Write(_apiId);
|
||||||
|
Serializers.String.write(writer, _apiHash);
|
||||||
|
Serializers.String.write(writer, _langCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnResponse(BinaryReader reader)
|
||||||
|
{
|
||||||
|
var boolTrue = 0x997275b5;
|
||||||
|
var dataCode = reader.ReadUInt32(); // 0x2215bcbd
|
||||||
|
_phoneRegistered = reader.ReadUInt32() == boolTrue;
|
||||||
|
_phoneCodeHash = Serializers.String.read(reader);
|
||||||
|
var sendCodeTimeout = reader.ReadInt32();
|
||||||
|
var isPassword = reader.ReadUInt32() == boolTrue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnException(Exception exception)
|
||||||
|
{
|
||||||
|
throw new NotImplementedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool Confirmed => true;
|
||||||
|
public override bool Responded { get; }
|
||||||
|
}
|
||||||
|
}
|
||||||
45
TLSharp.Core/Requests/AuthSignInRequest.cs
Normal file
45
TLSharp.Core/Requests/AuthSignInRequest.cs
Normal file
|
|
@ -0,0 +1,45 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using TLSharp.Core.MTProto;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.Requests
|
||||||
|
{
|
||||||
|
public class AuthSignInRequest : MTProtoRequest
|
||||||
|
{
|
||||||
|
private readonly string _phoneNumber;
|
||||||
|
private readonly string _phoneCodeHash;
|
||||||
|
private readonly string _code;
|
||||||
|
public User user;
|
||||||
|
public int SessionExpires;
|
||||||
|
|
||||||
|
public AuthSignInRequest(string phoneNumber, string phoneCodeHash, string code)
|
||||||
|
{
|
||||||
|
_phoneNumber = phoneNumber;
|
||||||
|
_phoneCodeHash = phoneCodeHash;
|
||||||
|
_code = code;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnSend(BinaryWriter writer)
|
||||||
|
{
|
||||||
|
writer.Write(0xbcd51581);
|
||||||
|
Serializers.String.write(writer, _phoneNumber);
|
||||||
|
Serializers.String.write(writer, _phoneCodeHash);
|
||||||
|
Serializers.String.write(writer, _code);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnResponse(BinaryReader reader)
|
||||||
|
{
|
||||||
|
var dataCode = reader.ReadUInt32(); //0xf6b673a4
|
||||||
|
var expires = reader.ReadInt32();
|
||||||
|
user = TL.Parse<User>(reader);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnException(Exception exception)
|
||||||
|
{
|
||||||
|
throw new NotImplementedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool Confirmed => true;
|
||||||
|
public override bool Responded { get; }
|
||||||
|
}
|
||||||
|
}
|
||||||
62
TLSharp.Core/Requests/ImportContactRequest.cs
Normal file
62
TLSharp.Core/Requests/ImportContactRequest.cs
Normal file
|
|
@ -0,0 +1,62 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using TLSharp.Core.MTProto;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.Requests
|
||||||
|
{
|
||||||
|
public class ImportContactRequest : MTProtoRequest
|
||||||
|
{
|
||||||
|
private InputContact Contact { get; set; }
|
||||||
|
private bool Replace { get; set; }
|
||||||
|
|
||||||
|
public List<ImportedContact> imported;
|
||||||
|
public List<User> users;
|
||||||
|
|
||||||
|
public ImportContactRequest(InputContact contact, bool shouldReplace = true)
|
||||||
|
{
|
||||||
|
Contact = contact;
|
||||||
|
Replace = shouldReplace;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnSend(BinaryWriter writer)
|
||||||
|
{
|
||||||
|
writer.Write(0xda30b32d);
|
||||||
|
writer.Write(0x1cb5c415);
|
||||||
|
writer.Write(1);
|
||||||
|
Contact.Write(writer);
|
||||||
|
writer.Write(Replace ? 0x997275b5 : 0xbc799737);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnResponse(BinaryReader reader)
|
||||||
|
{
|
||||||
|
var code = reader.ReadUInt32();
|
||||||
|
var result = reader.ReadInt32(); // vector code
|
||||||
|
int imported_len = reader.ReadInt32();
|
||||||
|
this.imported = new List<ImportedContact>(imported_len);
|
||||||
|
for (int imported_index = 0; imported_index < imported_len; imported_index++)
|
||||||
|
{
|
||||||
|
ImportedContact imported_element;
|
||||||
|
imported_element = TL.Parse<ImportedContact>(reader);
|
||||||
|
this.imported.Add(imported_element);
|
||||||
|
}
|
||||||
|
reader.ReadInt32(); // vector code
|
||||||
|
int users_len = reader.ReadInt32();
|
||||||
|
this.users = new List<User>(users_len);
|
||||||
|
for (int users_index = 0; users_index < users_len; users_index++)
|
||||||
|
{
|
||||||
|
User users_element;
|
||||||
|
users_element = TL.Parse<User>(reader);
|
||||||
|
this.users.Add(users_element);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnException(Exception exception)
|
||||||
|
{
|
||||||
|
throw new NotImplementedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool Confirmed => true;
|
||||||
|
public override bool Responded { get; }
|
||||||
|
}
|
||||||
|
}
|
||||||
55
TLSharp.Core/Requests/InitConnectionRequest.cs
Normal file
55
TLSharp.Core/Requests/InitConnectionRequest.cs
Normal file
|
|
@ -0,0 +1,55 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using TLSharp.Core.MTProto;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.Requests
|
||||||
|
{
|
||||||
|
public class InitConnectionRequest : MTProtoRequest
|
||||||
|
{
|
||||||
|
private int _apiId;
|
||||||
|
public ConfigConstructor ConfigConstructor { get; set; }
|
||||||
|
|
||||||
|
public InitConnectionRequest(int apiId)
|
||||||
|
{
|
||||||
|
_apiId = apiId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnSend(BinaryWriter writer)
|
||||||
|
{
|
||||||
|
writer.Write(0x39620c41); // invokeWithLayer10#39620c41, invokeWithLayer11#a6b88fdf
|
||||||
|
writer.Write(0x69796de9); // initConnection
|
||||||
|
writer.Write(_apiId); // api id
|
||||||
|
Serializers.String.write(writer, "WinPhone Emulator"); // device model
|
||||||
|
Serializers.String.write(writer, "WinPhone 8.0"); // system version
|
||||||
|
Serializers.String.write(writer, "1.0-SNAPSHOT"); // app version
|
||||||
|
Serializers.String.write(writer, "en"); // lang code
|
||||||
|
|
||||||
|
writer.Write(0xc4f9186b); // help.getConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnResponse(BinaryReader reader)
|
||||||
|
{
|
||||||
|
uint code = reader.ReadUInt32();
|
||||||
|
ConfigConstructor config = new ConfigConstructor();
|
||||||
|
config.Read(reader);
|
||||||
|
|
||||||
|
ConfigConstructor = config;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnException(Exception exception)
|
||||||
|
{
|
||||||
|
throw new NotImplementedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool Responded
|
||||||
|
{
|
||||||
|
get { return true; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnSendSuccess()
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
public override bool Confirmed => true;
|
||||||
|
}
|
||||||
|
}
|
||||||
46
TLSharp.Core/Requests/MTProtoRequest.cs
Normal file
46
TLSharp.Core/Requests/MTProtoRequest.cs
Normal file
|
|
@ -0,0 +1,46 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.Requests
|
||||||
|
{
|
||||||
|
public abstract class MTProtoRequest
|
||||||
|
{
|
||||||
|
public MTProtoRequest()
|
||||||
|
{
|
||||||
|
Sended = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long MessageId { get; set; }
|
||||||
|
public int Sequence { get; set; }
|
||||||
|
|
||||||
|
public bool Dirty { get; set; }
|
||||||
|
|
||||||
|
public bool Sended { get; private set; }
|
||||||
|
public DateTime SendTime { get; private set; }
|
||||||
|
public bool ConfirmReceived { get; set; }
|
||||||
|
public abstract void OnSend(BinaryWriter writer);
|
||||||
|
public abstract void OnResponse(BinaryReader reader);
|
||||||
|
public abstract void OnException(Exception exception);
|
||||||
|
public abstract bool Confirmed { get; }
|
||||||
|
public abstract bool Responded { get; }
|
||||||
|
|
||||||
|
public virtual void OnSendSuccess()
|
||||||
|
{
|
||||||
|
SendTime = DateTime.Now;
|
||||||
|
Sended = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual void OnConfirm()
|
||||||
|
{
|
||||||
|
ConfirmReceived = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool NeedResend
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
return Dirty || (Confirmed && !ConfirmReceived && DateTime.Now - SendTime > TimeSpan.FromSeconds(3));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
46
TLSharp.Core/Requests/SendMessageRequest.cs
Normal file
46
TLSharp.Core/Requests/SendMessageRequest.cs
Normal file
|
|
@ -0,0 +1,46 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using TLSharp.Core.MTProto;
|
||||||
|
using TLSharp.Core.Utils;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.Requests
|
||||||
|
{
|
||||||
|
public class SendMessageRequest : MTProtoRequest
|
||||||
|
{
|
||||||
|
private InputPeer _peer;
|
||||||
|
private string _message;
|
||||||
|
|
||||||
|
public SendMessageRequest(InputPeer peer, string message)
|
||||||
|
{
|
||||||
|
_peer = peer;
|
||||||
|
_message = message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnSend(BinaryWriter writer)
|
||||||
|
{
|
||||||
|
long random_id = Helpers.GenerateRandomLong();
|
||||||
|
writer.Write(0x4cde0aab);
|
||||||
|
_peer.Write(writer);
|
||||||
|
Serializers.String.write(writer, _message);
|
||||||
|
writer.Write(random_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnResponse(BinaryReader reader)
|
||||||
|
{
|
||||||
|
var code = reader.ReadUInt32();
|
||||||
|
|
||||||
|
var id = reader.ReadInt32();
|
||||||
|
var date = reader.ReadInt32();
|
||||||
|
var pts = reader.ReadInt32();
|
||||||
|
var seq = reader.ReadInt32();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnException(Exception exception)
|
||||||
|
{
|
||||||
|
throw new NotImplementedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool Confirmed => true;
|
||||||
|
public override bool Responded { get; }
|
||||||
|
}
|
||||||
|
}
|
||||||
180
TLSharp.Core/Session.cs
Normal file
180
TLSharp.Core/Session.cs
Normal file
|
|
@ -0,0 +1,180 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using TLSharp.Core.MTProto;
|
||||||
|
using TLSharp.Core.MTProto.Crypto;
|
||||||
|
|
||||||
|
namespace TLSharp.Core
|
||||||
|
{
|
||||||
|
public interface ISessionStore
|
||||||
|
{
|
||||||
|
void Save(Session session);
|
||||||
|
Session Load(string sessionUserId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public class FileSessionStore : ISessionStore
|
||||||
|
{
|
||||||
|
public void Save(Session session)
|
||||||
|
{
|
||||||
|
using (var stream = new FileStream($"{session.SessionUserId}.dat", FileMode.OpenOrCreate))
|
||||||
|
{
|
||||||
|
var result = session.ToBytes();
|
||||||
|
stream.Write(result, 0, result.Length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Session Load(string sessionUserId)
|
||||||
|
{
|
||||||
|
using (var stream = new FileStream($"{sessionUserId}.dat", FileMode.Open))
|
||||||
|
{
|
||||||
|
var buffer = new byte[2048];
|
||||||
|
stream.Read(buffer, 0, 2048);
|
||||||
|
|
||||||
|
return Session.FromBytes(buffer, this, sessionUserId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class FakeSessionStore : ISessionStore
|
||||||
|
{
|
||||||
|
public void Save(Session session)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public Session Load(string sessionUserId)
|
||||||
|
{
|
||||||
|
throw new NotImplementedException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class Session
|
||||||
|
{
|
||||||
|
public string SessionUserId { get; set; }
|
||||||
|
public AuthKey AuthKey { get; set; }
|
||||||
|
public ulong Id { get; set; }
|
||||||
|
public int Sequence { get; set; }
|
||||||
|
public ulong Salt { get; set; }
|
||||||
|
public int TimeOffset { get; set; }
|
||||||
|
public long LastMessageId { get; set; }
|
||||||
|
public int SessionExpires { get; set; }
|
||||||
|
public User User { get; set; }
|
||||||
|
private Random random;
|
||||||
|
|
||||||
|
private ISessionStore _store;
|
||||||
|
|
||||||
|
private Session(ISessionStore store)
|
||||||
|
{
|
||||||
|
random = new Random();
|
||||||
|
_store = store;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] ToBytes()
|
||||||
|
{
|
||||||
|
using (var stream = new MemoryStream())
|
||||||
|
using (var writer = new BinaryWriter(stream))
|
||||||
|
{
|
||||||
|
writer.Write(Id);
|
||||||
|
writer.Write(Sequence);
|
||||||
|
writer.Write(Salt);
|
||||||
|
writer.Write(LastMessageId);
|
||||||
|
writer.Write(TimeOffset);
|
||||||
|
if (User != null)
|
||||||
|
{
|
||||||
|
writer.Write(1);
|
||||||
|
writer.Write(SessionExpires);
|
||||||
|
User.Write(writer);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
writer.Write(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
Serializers.Bytes.write(writer, AuthKey.Data);
|
||||||
|
|
||||||
|
return stream.ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Session FromBytes(byte[] buffer, ISessionStore store, string sessionUserId)
|
||||||
|
{
|
||||||
|
using (var stream = new MemoryStream(buffer))
|
||||||
|
using (var reader = new BinaryReader(stream))
|
||||||
|
{
|
||||||
|
var id = reader.ReadUInt64();
|
||||||
|
var sequence = reader.ReadInt32();
|
||||||
|
var salt = reader.ReadUInt64();
|
||||||
|
var lastMessageId = reader.ReadInt64();
|
||||||
|
var timeOffset = reader.ReadInt32();
|
||||||
|
|
||||||
|
var isAuthExsist = reader.ReadInt32() == 1;
|
||||||
|
int sessionExpires = 0;
|
||||||
|
User user = null;
|
||||||
|
if (isAuthExsist)
|
||||||
|
{
|
||||||
|
sessionExpires = reader.ReadInt32();
|
||||||
|
user = TL.Parse<User>(reader);
|
||||||
|
}
|
||||||
|
|
||||||
|
var authData = Serializers.Bytes.read(reader);
|
||||||
|
|
||||||
|
return new Session(store)
|
||||||
|
{
|
||||||
|
AuthKey = new AuthKey(authData),
|
||||||
|
Id = id,
|
||||||
|
Salt = salt,
|
||||||
|
Sequence = sequence,
|
||||||
|
LastMessageId = lastMessageId,
|
||||||
|
TimeOffset = timeOffset,
|
||||||
|
SessionExpires = sessionExpires,
|
||||||
|
User = user,
|
||||||
|
SessionUserId = sessionUserId
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Save()
|
||||||
|
{
|
||||||
|
_store.Save(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Session TryLoadOrCreateNew(ISessionStore store, string sessionUserId)
|
||||||
|
{
|
||||||
|
Session session;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
session = store.Load(sessionUserId);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
session = new Session(store) { Id = GenerateRandomUlong(), SessionUserId = sessionUserId };
|
||||||
|
}
|
||||||
|
|
||||||
|
return session;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ulong GenerateRandomUlong()
|
||||||
|
{
|
||||||
|
var random = new Random();
|
||||||
|
ulong rand = (((ulong)random.Next()) << 32) | ((ulong)random.Next());
|
||||||
|
return rand;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long GetNewMessageId()
|
||||||
|
{
|
||||||
|
long time = Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds);
|
||||||
|
long newMessageId = ((time / 1000 + TimeOffset) << 32) |
|
||||||
|
((time % 1000) << 22) |
|
||||||
|
(random.Next(524288) << 2); // 2^19
|
||||||
|
// [ unix timestamp : 32 bit] [ milliseconds : 10 bit ] [ buffer space : 1 bit ] [ random : 19 bit ] [ msg_id type : 2 bit ] = [ msg_id : 64 bit ]
|
||||||
|
|
||||||
|
if (LastMessageId >= newMessageId)
|
||||||
|
{
|
||||||
|
newMessageId = LastMessageId + 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
LastMessageId = newMessageId;
|
||||||
|
return newMessageId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
89
TLSharp.Core/TLSharp.Core.csproj
Normal file
89
TLSharp.Core/TLSharp.Core.csproj
Normal file
|
|
@ -0,0 +1,89 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||||
|
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||||
|
<PropertyGroup>
|
||||||
|
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||||
|
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||||
|
<ProjectGuid>{400D2544-1CC6-4D8A-A62C-2292D9947A16}</ProjectGuid>
|
||||||
|
<OutputType>Library</OutputType>
|
||||||
|
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||||
|
<RootNamespace>TLSharp.Core</RootNamespace>
|
||||||
|
<AssemblyName>TLSharp.Core</AssemblyName>
|
||||||
|
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
|
||||||
|
<FileAlignment>512</FileAlignment>
|
||||||
|
</PropertyGroup>
|
||||||
|
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||||
|
<DebugSymbols>true</DebugSymbols>
|
||||||
|
<DebugType>full</DebugType>
|
||||||
|
<Optimize>false</Optimize>
|
||||||
|
<OutputPath>bin\Debug\</OutputPath>
|
||||||
|
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||||
|
<ErrorReport>prompt</ErrorReport>
|
||||||
|
<WarningLevel>4</WarningLevel>
|
||||||
|
</PropertyGroup>
|
||||||
|
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||||
|
<DebugType>pdbonly</DebugType>
|
||||||
|
<Optimize>true</Optimize>
|
||||||
|
<OutputPath>bin\Release\</OutputPath>
|
||||||
|
<DefineConstants>TRACE</DefineConstants>
|
||||||
|
<ErrorReport>prompt</ErrorReport>
|
||||||
|
<WarningLevel>4</WarningLevel>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<Reference Include="Ionic.ZLib, Version=2.0.0.14, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<HintPath>..\packages\MarkerMetro.Unity.Ionic.Zlib.2.0.0.14\lib\net35\Ionic.ZLib.dll</HintPath>
|
||||||
|
<Private>True</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="System" />
|
||||||
|
<Reference Include="System.Core" />
|
||||||
|
<Reference Include="System.Xml.Linq" />
|
||||||
|
<Reference Include="System.Data.DataSetExtensions" />
|
||||||
|
<Reference Include="Microsoft.CSharp" />
|
||||||
|
<Reference Include="System.Data" />
|
||||||
|
<Reference Include="System.Net.Http" />
|
||||||
|
<Reference Include="System.Xml" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<Compile Include="Auth\Authenticator.cs" />
|
||||||
|
<Compile Include="Auth\Step1_PQRequest.cs" />
|
||||||
|
<Compile Include="Auth\Step2_DHExchange.cs" />
|
||||||
|
<Compile Include="Auth\Step3_CompleteDHExchange.cs" />
|
||||||
|
<Compile Include="MTProto\Crypto\AES.cs" />
|
||||||
|
<Compile Include="MTProto\Crypto\AuthKey.cs" />
|
||||||
|
<Compile Include="MTProto\Crypto\BigInteger.cs" />
|
||||||
|
<Compile Include="MTProto\Crypto\Crc32.cs" />
|
||||||
|
<Compile Include="MTProto\Crypto\Factorizator.cs" />
|
||||||
|
<Compile Include="MTProto\Crypto\MD5Digest.cs" />
|
||||||
|
<Compile Include="MTProto\Crypto\RSA.cs" />
|
||||||
|
<Compile Include="MTProto\Crypto\Salt.cs" />
|
||||||
|
<Compile Include="MTProto\Serializers.cs" />
|
||||||
|
<Compile Include="MTProto\TL.cs" />
|
||||||
|
<Compile Include="Network\MtProtoPlainSender.cs" />
|
||||||
|
<Compile Include="Network\MtProtoSender.cs" />
|
||||||
|
<Compile Include="Network\TcpMessage.cs" />
|
||||||
|
<Compile Include="Network\TcpTransport.cs" />
|
||||||
|
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||||
|
<Compile Include="Requests\AckRequest.cs" />
|
||||||
|
<Compile Include="Requests\AuthCheckPhoneRequest.cs" />
|
||||||
|
<Compile Include="Requests\AuthSendCodeRequest.cs" />
|
||||||
|
<Compile Include="Requests\AuthSignInRequest.cs" />
|
||||||
|
<Compile Include="Requests\ImportContactRequest.cs" />
|
||||||
|
<Compile Include="Requests\InitConnectionRequest.cs" />
|
||||||
|
<Compile Include="Requests\MTProtoRequest.cs" />
|
||||||
|
<Compile Include="Requests\SendMessageRequest.cs" />
|
||||||
|
<Compile Include="Session.cs" />
|
||||||
|
<Compile Include="TelegramClient.cs" />
|
||||||
|
<Compile Include="Utils\Helpers.cs" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<None Include="packages.config" />
|
||||||
|
</ItemGroup>
|
||||||
|
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||||
|
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||||
|
Other similar extension points exist, see Microsoft.Common.targets.
|
||||||
|
<Target Name="BeforeBuild">
|
||||||
|
</Target>
|
||||||
|
<Target Name="AfterBuild">
|
||||||
|
</Target>
|
||||||
|
-->
|
||||||
|
</Project>
|
||||||
107
TLSharp.Core/TelegramClient.cs
Normal file
107
TLSharp.Core/TelegramClient.cs
Normal file
|
|
@ -0,0 +1,107 @@
|
||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using TLSharp.Core.Auth;
|
||||||
|
using TLSharp.Core.MTProto;
|
||||||
|
using TLSharp.Core.MTProto.Crypto;
|
||||||
|
using TLSharp.Core.Network;
|
||||||
|
using TLSharp.Core.Requests;
|
||||||
|
|
||||||
|
namespace TLSharp.Core
|
||||||
|
{
|
||||||
|
public class TelegramClient
|
||||||
|
{
|
||||||
|
private MtProtoSender _sender;
|
||||||
|
private AuthKey _key;
|
||||||
|
private readonly TcpTransport _transport;
|
||||||
|
private string _apiHash = "_your_hash";
|
||||||
|
private int _apiId = 0;
|
||||||
|
private Session _session;
|
||||||
|
|
||||||
|
public TelegramClient(ISessionStore store, string sessionUserId)
|
||||||
|
{
|
||||||
|
_transport = new TcpTransport();
|
||||||
|
_session = Session.TryLoadOrCreateNew(store, sessionUserId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> Connect()
|
||||||
|
{
|
||||||
|
if (_session.AuthKey == null)
|
||||||
|
{
|
||||||
|
var result = await Authenticator.DoAuthentication(_transport);
|
||||||
|
_session.AuthKey = result.AuthKey;
|
||||||
|
_session.TimeOffset = result.TimeOffset;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
_sender = new MtProtoSender(_transport, _session);
|
||||||
|
|
||||||
|
var request = new InitConnectionRequest(_apiId);
|
||||||
|
|
||||||
|
await _sender.Send(request);
|
||||||
|
await _sender.Recieve(request);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsUserAuthorized()
|
||||||
|
{
|
||||||
|
return _session.User != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> IsPhoneRegistered(string phoneNumber)
|
||||||
|
{
|
||||||
|
if (_sender == null)
|
||||||
|
throw new InvalidOperationException("Not connected!");
|
||||||
|
|
||||||
|
var authCheckPhoneRequest = new AuthCheckPhoneRequest(phoneNumber);
|
||||||
|
await _sender.Send(authCheckPhoneRequest);
|
||||||
|
await _sender.Recieve(authCheckPhoneRequest);
|
||||||
|
|
||||||
|
return authCheckPhoneRequest._phoneRegistered;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<string> SendCodeRequest(string phoneNumber)
|
||||||
|
{
|
||||||
|
var request = new AuthSendCodeRequest(phoneNumber, 5, _apiId, _apiHash, "en");
|
||||||
|
await _sender.Send(request);
|
||||||
|
await _sender.Recieve(request);
|
||||||
|
|
||||||
|
return request._phoneCodeHash;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<User> MakeAuth(string phoneNumber, string phoneHash, string code)
|
||||||
|
{
|
||||||
|
var request = new AuthSignInRequest(phoneNumber, phoneHash, code);
|
||||||
|
await _sender.Send(request);
|
||||||
|
await _sender.Recieve(request);
|
||||||
|
|
||||||
|
_session.SessionExpires = request.SessionExpires;
|
||||||
|
_session.User = request.user;
|
||||||
|
|
||||||
|
_session.Save();
|
||||||
|
|
||||||
|
return request.user;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<int?> ImportContact(string phoneNumber)
|
||||||
|
{
|
||||||
|
var request = new ImportContactRequest(new InputPhoneContactConstructor(0, phoneNumber, "My Test Name", string.Empty));
|
||||||
|
await _sender.Send(request);
|
||||||
|
await _sender.Recieve(request);
|
||||||
|
|
||||||
|
var importedUser = request.users.FirstOrDefault();
|
||||||
|
|
||||||
|
return importedUser == null ? (int?) null : ((UserContactConstructor) importedUser).id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task SendMessage(int id, string message)
|
||||||
|
{
|
||||||
|
var request = new SendMessageRequest(new InputPeerContactConstructor(id), message );
|
||||||
|
|
||||||
|
await _sender.Send(request);
|
||||||
|
await _sender.Recieve(request);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
85
TLSharp.Core/Utils/Helpers.cs
Normal file
85
TLSharp.Core/Utils/Helpers.cs
Normal file
|
|
@ -0,0 +1,85 @@
|
||||||
|
using System;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using TLSharp.Core.MTProto.Crypto;
|
||||||
|
|
||||||
|
namespace TLSharp.Core.Utils
|
||||||
|
{
|
||||||
|
public class Helpers {
|
||||||
|
private static Random random = new Random();
|
||||||
|
|
||||||
|
public static ulong GenerateRandomUlong() {
|
||||||
|
ulong rand = (((ulong)random.Next()) << 32) | ((ulong)random.Next());
|
||||||
|
return rand;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static long GenerateRandomLong() {
|
||||||
|
long rand = (((long)random.Next()) << 32) | ((long)random.Next());
|
||||||
|
return rand;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] GenerateRandomBytes(int num) {
|
||||||
|
byte[] data = new byte[num];
|
||||||
|
random.NextBytes(data);
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static AESKeyData CalcKey(byte[] sharedKey, byte[] msgKey, bool client) {
|
||||||
|
int x = client ? 0 : 8;
|
||||||
|
byte[] buffer = new byte[48];
|
||||||
|
|
||||||
|
Array.Copy(msgKey, 0, buffer, 0, 16); // buffer[0:16] = msgKey
|
||||||
|
Array.Copy(sharedKey, x, buffer, 16, 32); // buffer[16:48] = authKey[x:x+32]
|
||||||
|
byte[] sha1a = sha1(buffer); // sha1a = sha1(buffer)
|
||||||
|
|
||||||
|
Array.Copy(sharedKey, 32 + x, buffer, 0, 16); // buffer[0:16] = authKey[x+32:x+48]
|
||||||
|
Array.Copy(msgKey, 0, buffer, 16, 16); // buffer[16:32] = msgKey
|
||||||
|
Array.Copy(sharedKey, 48 + x, buffer, 32, 16); // buffer[32:48] = authKey[x+48:x+64]
|
||||||
|
byte[] sha1b = sha1(buffer); // sha1b = sha1(buffer)
|
||||||
|
|
||||||
|
Array.Copy(sharedKey, 64 + x, buffer, 0, 32); // buffer[0:32] = authKey[x+64:x+96]
|
||||||
|
Array.Copy(msgKey, 0, buffer, 32, 16); // buffer[32:48] = msgKey
|
||||||
|
byte[] sha1c = sha1(buffer); // sha1c = sha1(buffer)
|
||||||
|
|
||||||
|
Array.Copy(msgKey, 0, buffer, 0, 16); // buffer[0:16] = msgKey
|
||||||
|
Array.Copy(sharedKey, 96 + x, buffer, 16, 32); // buffer[16:48] = authKey[x+96:x+128]
|
||||||
|
byte[] sha1d = sha1(buffer); // sha1d = sha1(buffer)
|
||||||
|
|
||||||
|
byte[] key = new byte[32]; // key = sha1a[0:8] + sha1b[8:20] + sha1c[4:16]
|
||||||
|
Array.Copy(sha1a, 0, key, 0, 8);
|
||||||
|
Array.Copy(sha1b, 8, key, 8, 12);
|
||||||
|
Array.Copy(sha1c, 4, key, 20, 12);
|
||||||
|
|
||||||
|
byte[] iv = new byte[32]; // iv = sha1a[8:20] + sha1b[0:8] + sha1c[16:20] + sha1d[0:8]
|
||||||
|
Array.Copy(sha1a, 8, iv, 0, 12);
|
||||||
|
Array.Copy(sha1b, 0, iv, 12, 8);
|
||||||
|
Array.Copy(sha1c, 16, iv, 20, 4);
|
||||||
|
Array.Copy(sha1d, 0, iv, 24, 8);
|
||||||
|
|
||||||
|
return new AESKeyData(key, iv);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] CalcMsgKey(byte[] data) {
|
||||||
|
byte[] msgKey = new byte[16];
|
||||||
|
Array.Copy(sha1(data), 4, msgKey, 0, 16);
|
||||||
|
return msgKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] CalcMsgKey(byte[] data, int offset, int limit) {
|
||||||
|
byte[] msgKey = new byte[16];
|
||||||
|
Array.Copy(sha1(data, offset, limit), 4, msgKey, 0, 16);
|
||||||
|
return msgKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] sha1(byte[] data) {
|
||||||
|
using (SHA1 sha1 = new SHA1Managed()) {
|
||||||
|
return sha1.ComputeHash(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] sha1(byte[] data, int offset, int limit) {
|
||||||
|
using (SHA1 sha1 = new SHA1Managed()) {
|
||||||
|
return sha1.ComputeHash(data, offset, limit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
5
TLSharp.Core/packages.config
Normal file
5
TLSharp.Core/packages.config
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<packages>
|
||||||
|
<package id="DotNetZip" version="1.9.3" targetFramework="net451" />
|
||||||
|
<package id="MarkerMetro.Unity.Ionic.Zlib" version="2.0.0.14" targetFramework="net452" />
|
||||||
|
</packages>
|
||||||
121
TLSharp.Tests/NotificatioClientTests.cs
Normal file
121
TLSharp.Tests/NotificatioClientTests.cs
Normal file
|
|
@ -0,0 +1,121 @@
|
||||||
|
using System;
|
||||||
|
using System.Configuration;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||||
|
using TLSharp.Core;
|
||||||
|
using TLSharp.Core.Auth;
|
||||||
|
using TLSharp.Core.Network;
|
||||||
|
|
||||||
|
namespace TLSharp.Tests
|
||||||
|
{
|
||||||
|
[TestClass]
|
||||||
|
public class NotificatioClientTests
|
||||||
|
{
|
||||||
|
public string NumberToAuthenticate { get; set; }
|
||||||
|
public string RegisteredNumber { get; set; }
|
||||||
|
public string UnregisteredNumber { get; set; }
|
||||||
|
|
||||||
|
[TestInitialize]
|
||||||
|
public void Init()
|
||||||
|
{
|
||||||
|
// Setup your phone numbers in app.config
|
||||||
|
NumberToAuthenticate = ConfigurationManager.AppSettings["numberToAuthenticate"];
|
||||||
|
RegisteredNumber = ConfigurationManager.AppSettings["registeredNumber"];
|
||||||
|
UnregisteredNumber = ConfigurationManager.AppSettings["unregisteredNumber"];
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task AuthUser()
|
||||||
|
{
|
||||||
|
var store = new FileSessionStore();
|
||||||
|
var client = new TelegramClient(store, "session");
|
||||||
|
await client.Connect();
|
||||||
|
|
||||||
|
var hash = await client.SendCodeRequest(NumberToAuthenticate);
|
||||||
|
var code = "123"; // you can change code in debugger
|
||||||
|
|
||||||
|
var user = await client.MakeAuth(NumberToAuthenticate, hash, code);
|
||||||
|
|
||||||
|
Assert.IsNotNull(user);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task CheckPhones()
|
||||||
|
{
|
||||||
|
var store = new FileSessionStore();
|
||||||
|
var client = new Core.TelegramClient(store, "session");
|
||||||
|
await client.Connect();
|
||||||
|
|
||||||
|
var phoneList = new string[]
|
||||||
|
{
|
||||||
|
RegisteredNumber,
|
||||||
|
NumberToAuthenticate
|
||||||
|
};
|
||||||
|
|
||||||
|
var rand = new Random();
|
||||||
|
foreach (var phone in phoneList)
|
||||||
|
{
|
||||||
|
var result = await client.IsPhoneRegistered(phone);
|
||||||
|
Thread.Sleep(rand.Next(9) * 1000);
|
||||||
|
if (result)
|
||||||
|
Console.WriteLine($"{phone} - OK");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task ImportContact()
|
||||||
|
{
|
||||||
|
// User should be already authenticated!
|
||||||
|
|
||||||
|
var store = new FileSessionStore();
|
||||||
|
var client = new Core.TelegramClient(store, "session");
|
||||||
|
await client.Connect();
|
||||||
|
|
||||||
|
Assert.IsTrue(client.IsUserAuthorized());
|
||||||
|
|
||||||
|
var res = await client.ImportContact(RegisteredNumber);
|
||||||
|
|
||||||
|
Assert.IsNotNull(res);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task SendMessage()
|
||||||
|
{
|
||||||
|
// User should be already authenticated!
|
||||||
|
|
||||||
|
var store = new FileSessionStore();
|
||||||
|
var client = new Core.TelegramClient(store, "session");
|
||||||
|
await client.Connect();
|
||||||
|
|
||||||
|
Assert.IsTrue(client.IsUserAuthorized());
|
||||||
|
|
||||||
|
var res = await client.ImportContact(RegisteredNumber);
|
||||||
|
|
||||||
|
Assert.IsNotNull(res);
|
||||||
|
|
||||||
|
await client.SendMessage(res.Value, "Test message from TelegramClient");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task TestConnection()
|
||||||
|
{
|
||||||
|
var store = new FakeSessionStore();
|
||||||
|
var client = new Core.TelegramClient(store, "");
|
||||||
|
|
||||||
|
Assert.IsTrue(await client.Connect());
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task AuthenticationWorks()
|
||||||
|
{
|
||||||
|
using (var transport = new TcpTransport())
|
||||||
|
{
|
||||||
|
var authKey = await Authenticator.DoAuthentication(transport);
|
||||||
|
|
||||||
|
Assert.IsNotNull(authKey.AuthKey.Data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
36
TLSharp.Tests/Properties/AssemblyInfo.cs
Normal file
36
TLSharp.Tests/Properties/AssemblyInfo.cs
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
|
// General Information about an assembly is controlled through the following
|
||||||
|
// set of attributes. Change these attribute values to modify the information
|
||||||
|
// associated with an assembly.
|
||||||
|
[assembly: AssemblyTitle("TLSharp.Tests")]
|
||||||
|
[assembly: AssemblyDescription("")]
|
||||||
|
[assembly: AssemblyConfiguration("")]
|
||||||
|
[assembly: AssemblyCompany("")]
|
||||||
|
[assembly: AssemblyProduct("TLSharp.Tests")]
|
||||||
|
[assembly: AssemblyCopyright("Copyright © 2015")]
|
||||||
|
[assembly: AssemblyTrademark("")]
|
||||||
|
[assembly: AssemblyCulture("")]
|
||||||
|
|
||||||
|
// Setting ComVisible to false makes the types in this assembly not visible
|
||||||
|
// to COM components. If you need to access a type in this assembly from
|
||||||
|
// COM, set the ComVisible attribute to true on that type.
|
||||||
|
[assembly: ComVisible(false)]
|
||||||
|
|
||||||
|
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||||
|
[assembly: Guid("de5c0467-ee99-4734-95f2-eff7a0b99924")]
|
||||||
|
|
||||||
|
// Version information for an assembly consists of the following four values:
|
||||||
|
//
|
||||||
|
// Major Version
|
||||||
|
// Minor Version
|
||||||
|
// Build Number
|
||||||
|
// Revision
|
||||||
|
//
|
||||||
|
// You can specify all the values or you can default the Build and Revision Numbers
|
||||||
|
// by using the '*' as shown below:
|
||||||
|
// [assembly: AssemblyVersion("1.0.*")]
|
||||||
|
[assembly: AssemblyVersion("1.0.0.0")]
|
||||||
|
[assembly: AssemblyFileVersion("1.0.0.0")]
|
||||||
94
TLSharp.Tests/TLSharp.Tests.csproj
Normal file
94
TLSharp.Tests/TLSharp.Tests.csproj
Normal file
|
|
@ -0,0 +1,94 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||||
|
<PropertyGroup>
|
||||||
|
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||||
|
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||||
|
<ProjectGuid>{DE5C0467-EE99-4734-95F2-EFF7A0B99924}</ProjectGuid>
|
||||||
|
<OutputType>Library</OutputType>
|
||||||
|
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||||
|
<RootNamespace>TLSharp.Tests</RootNamespace>
|
||||||
|
<AssemblyName>TLSharp.Tests</AssemblyName>
|
||||||
|
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
|
||||||
|
<FileAlignment>512</FileAlignment>
|
||||||
|
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
|
||||||
|
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
|
||||||
|
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
|
||||||
|
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
|
||||||
|
<IsCodedUITest>False</IsCodedUITest>
|
||||||
|
<TestProjectType>UnitTest</TestProjectType>
|
||||||
|
</PropertyGroup>
|
||||||
|
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||||
|
<DebugSymbols>true</DebugSymbols>
|
||||||
|
<DebugType>full</DebugType>
|
||||||
|
<Optimize>false</Optimize>
|
||||||
|
<OutputPath>bin\Debug\</OutputPath>
|
||||||
|
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||||
|
<ErrorReport>prompt</ErrorReport>
|
||||||
|
<WarningLevel>4</WarningLevel>
|
||||||
|
</PropertyGroup>
|
||||||
|
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||||
|
<DebugType>pdbonly</DebugType>
|
||||||
|
<Optimize>true</Optimize>
|
||||||
|
<OutputPath>bin\Release\</OutputPath>
|
||||||
|
<DefineConstants>TRACE</DefineConstants>
|
||||||
|
<ErrorReport>prompt</ErrorReport>
|
||||||
|
<WarningLevel>4</WarningLevel>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<Reference Include="System" />
|
||||||
|
<Reference Include="System.Configuration" />
|
||||||
|
</ItemGroup>
|
||||||
|
<Choose>
|
||||||
|
<When Condition="('$(VisualStudioVersion)' == '10.0' or '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'">
|
||||||
|
<ItemGroup>
|
||||||
|
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
|
||||||
|
</ItemGroup>
|
||||||
|
</When>
|
||||||
|
<Otherwise>
|
||||||
|
<ItemGroup>
|
||||||
|
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Otherwise>
|
||||||
|
</Choose>
|
||||||
|
<ItemGroup>
|
||||||
|
<Compile Include="NotificatioClientTests.cs" />
|
||||||
|
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<None Include="app.config" />
|
||||||
|
<None Include="packages.config" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\TLSharp.Core\TLSharp.Core.csproj">
|
||||||
|
<Project>{400d2544-1cc6-4d8a-a62c-2292d9947a16}</Project>
|
||||||
|
<Name>TLSharp.Core</Name>
|
||||||
|
</ProjectReference>
|
||||||
|
</ItemGroup>
|
||||||
|
<Choose>
|
||||||
|
<When Condition="'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'">
|
||||||
|
<ItemGroup>
|
||||||
|
<Reference Include="Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||||
|
<Private>False</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||||
|
<Private>False</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||||
|
<Private>False</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||||
|
<Private>False</Private>
|
||||||
|
</Reference>
|
||||||
|
</ItemGroup>
|
||||||
|
</When>
|
||||||
|
</Choose>
|
||||||
|
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
|
||||||
|
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||||
|
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||||
|
Other similar extension points exist, see Microsoft.Common.targets.
|
||||||
|
<Target Name="BeforeBuild">
|
||||||
|
</Target>
|
||||||
|
<Target Name="AfterBuild">
|
||||||
|
</Target>
|
||||||
|
-->
|
||||||
|
</Project>
|
||||||
8
TLSharp.Tests/app.config
Normal file
8
TLSharp.Tests/app.config
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8" ?>
|
||||||
|
<configuration>
|
||||||
|
<appSettings>
|
||||||
|
<add key="numberToAuthenticate" value="" />
|
||||||
|
<add key="registeredNumber" value="" />
|
||||||
|
<add key="unregisteredNumber" value="" />
|
||||||
|
</appSettings>
|
||||||
|
</configuration>
|
||||||
3
TLSharp.Tests/packages.config
Normal file
3
TLSharp.Tests/packages.config
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<packages>
|
||||||
|
</packages>
|
||||||
28
TLSharp.sln
Normal file
28
TLSharp.sln
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
|
||||||
|
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||||
|
# Visual Studio 14
|
||||||
|
VisualStudioVersion = 14.0.23107.0
|
||||||
|
MinimumVisualStudioVersion = 10.0.40219.1
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TLSharp.Core", "TLSharp.Core\TLSharp.Core.csproj", "{400D2544-1CC6-4D8A-A62C-2292D9947A16}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TLSharp.Tests", "TLSharp.Tests\TLSharp.Tests.csproj", "{DE5C0467-EE99-4734-95F2-EFF7A0B99924}"
|
||||||
|
EndProject
|
||||||
|
Global
|
||||||
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
|
Debug|Any CPU = Debug|Any CPU
|
||||||
|
Release|Any CPU = Release|Any CPU
|
||||||
|
EndGlobalSection
|
||||||
|
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||||
|
{400D2544-1CC6-4D8A-A62C-2292D9947A16}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{400D2544-1CC6-4D8A-A62C-2292D9947A16}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{400D2544-1CC6-4D8A-A62C-2292D9947A16}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{400D2544-1CC6-4D8A-A62C-2292D9947A16}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{DE5C0467-EE99-4734-95F2-EFF7A0B99924}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{DE5C0467-EE99-4734-95F2-EFF7A0B99924}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{DE5C0467-EE99-4734-95F2-EFF7A0B99924}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{DE5C0467-EE99-4734-95F2-EFF7A0B99924}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
EndGlobalSection
|
||||||
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
|
HideSolutionNode = FALSE
|
||||||
|
EndGlobalSection
|
||||||
|
EndGlobal
|
||||||
Loading…
Reference in a new issue