2017-05-17 21:06:16 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using System.Numerics;
|
2017-05-18 14:00:15 +00:00
|
|
|
|
using Square;
|
2017-05-17 21:06:16 +00:00
|
|
|
|
|
2017-05-22 03:27:32 +00:00
|
|
|
|
namespace Server.Encryption {
|
2017-05-17 21:06:16 +00:00
|
|
|
|
class KeyExchange {
|
|
|
|
|
private BigInteger Secret;
|
2017-05-18 14:00:15 +00:00
|
|
|
|
public BigInteger Generator { get; private set; } = 2;
|
2017-05-17 21:06:16 +00:00
|
|
|
|
public BigInteger Modulus { get; private set; }
|
2017-05-20 23:33:39 +00:00
|
|
|
|
public BigInteger PrivateKey { get; private set; } = BigInteger.Zero;
|
|
|
|
|
public bool Succeeded {
|
|
|
|
|
get => !PrivateKey.IsZero;
|
|
|
|
|
}
|
2017-05-17 21:06:16 +00:00
|
|
|
|
|
2017-05-18 14:00:15 +00:00
|
|
|
|
public KeyExchange() {
|
|
|
|
|
Secret = RNG.NextPrime(512 / 8);
|
|
|
|
|
Modulus = RNG.NextPrime(512 / 8);
|
|
|
|
|
}
|
2017-05-18 21:03:35 +00:00
|
|
|
|
|
2017-05-20 23:33:39 +00:00
|
|
|
|
public Packet GenerateRequestPacket() {
|
|
|
|
|
return new Packet(Packet.kId.KeyExchange, Generator.ToHexString(), Modulus.ToHexString(), BigInteger.ModPow(Generator, Secret, Modulus).ToHexString());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public BigInteger ParseResponsePacket(Packet packet) {
|
|
|
|
|
if(packet.Id == Packet.kId.KeyExchange && packet.RegionCount != 1)
|
|
|
|
|
return -1;
|
2017-05-18 21:03:35 +00:00
|
|
|
|
|
2017-05-20 23:33:39 +00:00
|
|
|
|
if(!BigInteger.TryParse(packet[0], out BigInteger ClientKey))
|
|
|
|
|
return -1;
|
|
|
|
|
|
|
|
|
|
return (PrivateKey = BigInteger.ModPow(ClientKey, Secret, Modulus));
|
2017-05-19 21:02:39 +00:00
|
|
|
|
}
|
2017-05-17 21:06:16 +00:00
|
|
|
|
}
|
|
|
|
|
}
|