TLSharp/TLSharp.Core/MTProto/Crypto/AuthKey.cs

88 lines
2.6 KiB
C#
Raw Normal View History

2015-09-28 04:01:17 +02:00
using System;
using System.IO;
using System.Security.Cryptography;
2016-04-18 12:50:57 +02:00
namespace TLSharp.Core.MTProto.Crypto
{
public class AuthKey
{
2015-09-28 04:01:17 +02:00
private byte[] key;
private ulong keyId;
private ulong auxHash;
2016-04-18 12:50:57 +02:00
public AuthKey(BigInteger gab)
{
2015-09-28 04:01:17 +02:00
key = gab.ToByteArrayUnsigned();
2016-04-18 12:50:57 +02:00
using (SHA1 hash = new SHA1Managed())
{
using (MemoryStream hashStream = new MemoryStream(hash.ComputeHash(key), false))
{
using (BinaryReader hashReader = new BinaryReader(hashStream))
{
2015-09-28 04:01:17 +02:00
auxHash = hashReader.ReadUInt64();
hashReader.ReadBytes(4);
keyId = hashReader.ReadUInt64();
}
}
}
}
2016-04-18 12:50:57 +02:00
public AuthKey(byte[] data)
{
2015-09-28 04:01:17 +02:00
key = data;
2016-04-18 12:50:57 +02:00
using (SHA1 hash = new SHA1Managed())
{
using (MemoryStream hashStream = new MemoryStream(hash.ComputeHash(key), false))
{
using (BinaryReader hashReader = new BinaryReader(hashStream))
{
2015-09-28 04:01:17 +02:00
auxHash = hashReader.ReadUInt64();
hashReader.ReadBytes(4);
keyId = hashReader.ReadUInt64();
}
}
}
}
2016-04-18 12:50:57 +02:00
public byte[] CalcNewNonceHash(byte[] newNonce, int number)
{
using (MemoryStream buffer = new MemoryStream(100))
{
using (BinaryWriter bufferWriter = new BinaryWriter(buffer))
{
2015-09-28 04:01:17 +02:00
bufferWriter.Write(newNonce);
bufferWriter.Write((byte)number);
bufferWriter.Write(auxHash);
2016-04-18 12:50:57 +02:00
using (SHA1 sha1 = new SHA1Managed())
{
2015-09-28 04:01:17 +02:00
byte[] hash = sha1.ComputeHash(buffer.GetBuffer(), 0, (int)buffer.Position);
byte[] newNonceHash = new byte[16];
Array.Copy(hash, 4, newNonceHash, 0, 16);
return newNonceHash;
}
}
}
}
2016-04-18 12:50:57 +02:00
public byte[] Data
{
get
{
2015-09-28 04:01:17 +02:00
return key;
}
}
2016-04-18 12:50:57 +02:00
public ulong Id
{
get
{
2015-09-28 04:01:17 +02:00
return keyId;
}
}
2016-04-18 12:50:57 +02:00
public override string ToString()
{
2015-09-28 04:01:17 +02:00
return string.Format("(Key: {0}, KeyId: {1}, AuxHash: {2})", key, keyId, auxHash);
}
}
}