sockscape/server/Encryption/KeyExchange.cs

44 lines
1.3 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;
2017-05-17 21:06:16 +00:00
2017-05-25 21:08:21 +00:00
namespace CircleScape.Encryption {
2017-05-17 21:06:16 +00:00
class KeyExchange {
private BigInteger Secret;
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
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() {
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)
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
}
}