sockscape/server/Encryption/KeyExchange.cs

44 lines
1.4 KiB
C#
Raw Normal View History

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;
using Square;
using System.Globalization;
2017-05-17 21:06:16 +00:00
2017-05-25 21:08:21 +00:00
namespace CircleScape.Encryption {
2017-05-26 20:28:02 +00:00
class Key {
2017-05-30 21:05:02 +00:00
private readonly static BigInteger Secret = RNG.NextPrime(512 / 8);
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-26 20:28:02 +00:00
public Key() {
Modulus = RNG.NextPrime(512 / 8);
}
2017-05-18 21:03:35 +00:00
2017-05-20 23:33:39 +00:00
public Packet GenerateRequestPacket() {
2017-05-25 21:08:21 +00:00
return new Packet(
Packet.kId.KeyExchange,
Generator.ToHexString(),
Modulus.ToHexString(),
BigInteger.ModPow(Generator, Secret, Modulus).ToHexString()
);
2017-05-20 23:33:39 +00:00
}
public BigInteger ParseResponsePacket(Packet packet) {
if(packet.Id != Packet.kId.KeyExchange || packet.RegionCount != 1)
2017-05-20 23:33:39 +00:00
return -1;
2017-05-18 21:03:35 +00:00
if(!BigInteger.TryParse(packet[0], NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo, out BigInteger ClientKey))
2017-05-20 23:33:39 +00:00
return -1;
2017-05-20 23:33:39 +00:00
return (PrivateKey = BigInteger.ModPow(ClientKey, Secret, Modulus));
2017-05-19 21:02:39 +00:00
}
2017-05-17 21:06:16 +00:00
}
}