private ChainKey GetOrCreateChainKey(SessionState sessionState, IEcPublicKey theirEphemeral) { try { if (sessionState.HasReceiverChain(theirEphemeral)) { return(sessionState.GetReceiverChainKey(theirEphemeral)); } else { RootKey rootKey = sessionState.GetRootKey(); EcKeyPair ourEphemeral = sessionState.GetSenderRatchetKeyPair(); Pair <RootKey, ChainKey> receiverChain = rootKey.CreateChain(theirEphemeral, ourEphemeral); EcKeyPair ourNewEphemeral = Curve.GenerateKeyPair(); Pair <RootKey, ChainKey> senderChain = receiverChain.First().CreateChain(theirEphemeral, ourNewEphemeral); sessionState.SetRootKey(senderChain.First()); sessionState.AddReceiverChain(theirEphemeral, receiverChain.Second()); sessionState.SetPreviousCounter(Math.Max(sessionState.GetSenderChainKey().GetIndex() - 1, 0)); sessionState.SetSenderChain(ourNewEphemeral, senderChain.Second()); return(receiverChain.Second()); } } catch (InvalidKeyException e) { throw new InvalidMessageException(e); } }
public static void InitializeSession(SessionState sessionState, uint sessionVersion, AliceAxolotlParameters parameters) { try { sessionState.SetSessionVersion(sessionVersion); sessionState.SetRemoteIdentityKey(parameters.GetTheirIdentityKey()); sessionState.SetLocalIdentityKey(parameters.GetOurIdentityKey().GetPublicKey()); ECKeyPair sendingRatchetKey = Curve.GenerateKeyPair(); MemoryStream secrets = new MemoryStream(); if (sessionVersion >= 3) { byte[] discontinuityBytes = GetDiscontinuityBytes(); secrets.Write(discontinuityBytes, 0, discontinuityBytes.Length); } byte[] agree1 = Curve.CalculateAgreement(parameters.GetTheirSignedPreKey(), parameters.GetOurIdentityKey().GetPrivateKey()); byte[] agree2 = Curve.CalculateAgreement(parameters.GetTheirIdentityKey().GetPublicKey(), parameters.GetOurBaseKey().GetPrivateKey()); byte[] agree3 = Curve.CalculateAgreement(parameters.GetTheirSignedPreKey(), parameters.GetOurBaseKey().GetPrivateKey()); secrets.Write(agree1, 0, agree1.Length); secrets.Write(agree2, 0, agree2.Length); secrets.Write(agree3, 0, agree3.Length); if (sessionVersion >= 3 && parameters.GetTheirOneTimePreKey().HasValue) { byte[] agree4 = Curve.CalculateAgreement(parameters.GetTheirOneTimePreKey().ForceGetValue(), parameters.GetOurBaseKey().GetPrivateKey()); secrets.Write(agree4, 0, agree4.Length); } DerivedKeys derivedKeys = CalculateDerivedKeys(sessionVersion, secrets.ToArray()); Pair <RootKey, ChainKey> sendingChain = derivedKeys.GetRootKey().CreateChain(parameters.GetTheirRatchetKey(), sendingRatchetKey); sessionState.AddReceiverChain(parameters.GetTheirRatchetKey(), derivedKeys.GetChainKey()); sessionState.SetSenderChain(sendingRatchetKey, sendingChain.Second()); sessionState.SetRootKey(sendingChain.First()); } catch (IOException e) { throw new Exception(e.Message); } }