github.com/geph-official/geph2@v0.22.6-0.20210211030601-f527cb59b0df/libs/cshirt2/uniformdh.go (about) 1 package cshirt2 2 3 import ( 4 "crypto/rand" 5 "math/big" 6 ) 7 8 var dhGroup5 = func() *big.Int { 9 toret := big.NewInt(0) 10 toret.SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF", 16) 11 return toret 12 }() 13 14 type pubKey []byte 15 type secKey []byte 16 17 func udhSecret(lsk secKey, rpk pubKey) []byte { 18 bitlen := len(lsk) * 8 19 // checks 20 if bitlen != 1536 { 21 panic("Why are you trying to generate DH key with wrong bitlen?") 22 } 23 var group *big.Int 24 group = dhGroup5 25 return big.NewInt(0).Exp(big.NewInt(0).SetBytes(rpk), 26 big.NewInt(0).SetBytes(lsk), group).Bytes() 27 } 28 29 func dhGenKey() (pk pubKey, sk secKey) { 30 const bitlen = 1536 31 var group *big.Int 32 group = dhGroup5 33 // randomly generate even private key 34 pub := pubKey(make([]byte, bitlen/8)) 35 priv := secKey(make([]byte, bitlen/8)) 36 rand.Read(priv) 37 priv[bitlen/8-1] /= 2 38 priv[bitlen/8-1] *= 2 39 privBnum := big.NewInt(0).SetBytes(priv) 40 retry: 41 // generate public key 42 pubBnum := big.NewInt(0).Exp(big.NewInt(2), privBnum, group) 43 ggg := make([]byte, 1) 44 rand.Read(ggg) 45 if ggg[0]%2 == 0 { 46 pubBnum = big.NewInt(0).Sub(group, pubBnum) 47 } 48 // Obtain pubkey 49 candid := pubBnum.Bytes() 50 if len(candid) != len(pub) { 51 goto retry 52 } 53 copy(pub, candid) 54 globCacheLock.Lock() 55 defer globCacheLock.Unlock() 56 globCache.SetDefault(string(pk), false) 57 return pub, priv 58 }