From 7a46cf371e31b6020a3dbaa240e752e78b212495 Mon Sep 17 00:00:00 2001
From: "Richard T. Carback III" <rick.carback@gmail.com>
Date: Thu, 2 Dec 2021 02:08:07 +0000
Subject: [PATCH] Add function to generate session keys with DH and SIDH keys

---
 storage/e2e/key.go | 37 ++++++++++++++++++++++++++++++++++++-
 1 file changed, 36 insertions(+), 1 deletion(-)

diff --git a/storage/e2e/key.go b/storage/e2e/key.go
index 49900a09a..ed40e54e5 100644
--- a/storage/e2e/key.go
+++ b/storage/e2e/key.go
@@ -12,8 +12,42 @@ import (
 	e2eCrypto "gitlab.com/elixxir/crypto/e2e"
 	"gitlab.com/elixxir/crypto/hash"
 	"gitlab.com/elixxir/primitives/format"
+	"github.com/cloudflare/circl/dh/sidh"
+	"gitlab.com/elixxir/crypto/cyclic"
+	dh "gitlab.com/elixxir/crypto/diffieHellman"
+	jww "github.com/spf13/jwalterweatherman"
 )
 
+// GenerateE2ESessionBaseKey returns the baseKey symmetric encryption key root.
+// The baseKey is created by hashing the results of the diffie-helman (DH) key
+// exchange with the post-quantum secure Supersingular Isogeny DH exchange
+// results.
+func GenerateE2ESessionBaseKey(myDHPrivKey, theirDHPubKey *cyclic.Int,
+	dhGrp *cyclic.Group, mySIDHPrivKey *sidh.PrivateKey,
+	theirSIDHPubKey *sidh.PublicKey) *cyclic.Int {
+	// DH Key Gen
+	dhKey := dh.GenerateSessionKey(myDHPrivKey, theirDHPubKey, dhGrp)
+
+	// SIDH Key Gen
+	sidhKey := make([]byte, mySIDHPrivKey.SharedSecretSize())
+	mySIDHPrivKey.DeriveSecret(sidhKey, theirSIDHPubKey)
+
+	// Derive key
+	h := hash.CMixHash.New()
+	h.Write(dhKey.Bytes())
+	h.Write(sidhKey)
+	keyDigest := h.Sum(nil)
+	// NOTE: Sadly the baseKey was a full DH key, and that key was used
+	// to create an "IDF" as well as in key generation and potentially other
+	// downstream code. We use a KDF to limit scope of the change,'
+	// generating into the same group as DH to preserve any kind of
+	// downstream reliance on the size of the key for now.
+	baseKey := hash.ExpandKey(hash.CMixHash.New, dhGrp, keyDigest,
+		dhGrp.NewInt(1))
+
+	return baseKey
+}
+
 type Key struct {
 	// Links
 	session *Session
@@ -96,7 +130,8 @@ func (k *Key) denoteUse() {
 	k.session.useKey(k.keyNum)
 }
 
-// Generates the key and returns it
+// generateKey derives the current e2e key from the baseKey and the index
+// keyNum and returns it
 func (k *Key) generateKey() e2eCrypto.Key {
 	return e2eCrypto.DeriveKey(k.session.baseKey, k.keyNum,
 		k.session.relationshipFingerprint)
-- 
GitLab