MCPcopy Index your code
hub / github.com/TheAlgorithms/Go / dsaParameterGeneration

Method dsaParameterGeneration

cipher/dsa/dsa.go:50–103  ·  view source on GitHub ↗

Parameter generation for DSA 1. FIPS 186-4 specifies that the L and N values must be (1024, 160), (2048, 224), or (3072, 256) 2. Choose a N-bit prime q 3. Choose a L-bit prime p such that p-1 is a multiple of q 4. Choose an integer h randomly from the range [2, p-2] 5. Compute g = h^((p-1)/q) mod p

()

Source from the content-addressed store, hash-verified

48// 5. Compute g = h^((p-1)/q) mod p
49// 6. Return (p, q, g)
50func (dsa *dsa) dsaParameterGeneration() {
51 var err error
52 p, q, bigInt := new(big.Int), new(big.Int), new(big.Int)
53 one, g, h := big.NewInt(1), big.NewInt(1), big.NewInt(2)
54 pBytes := make([]byte, L/8)
55
56 // GPLoop is a label for the loop
57 // We use this loop to change the prime q if we don't find a prime p
58GPLoop:
59 for {
60 // 2. Choose a N-bit prime q
61 q, err = rand.Prime(rand.Reader, N)
62 if err != nil {
63 panic(err)
64 }
65
66 for i := 0; i < 4*L; i++ {
67 // 3. Choose a L-bit prime p such that p-1 is a multiple of q
68 // In this case we generate a random number of L bits
69 if _, err := io.ReadFull(rand.Reader, pBytes); err != nil {
70 panic(err)
71 }
72
73 // This are the minimum conditions for p being a possible prime
74 pBytes[len(pBytes)-1] |= 1 // p is odd
75 pBytes[0] |= 0x80 // p has the highest bit set
76 p.SetBytes(pBytes)
77
78 // Instead of using (p-1)%q == 0
79 // We ensure that p-1 is a multiple of q and validates if p is prime
80 bigInt.Mod(p, q)
81 bigInt.Sub(bigInt, one)
82 p.Sub(p, bigInt)
83 if p.BitLen() < L || !p.ProbablyPrime(numMRTests) { // Check if p is prime and has L bits
84 continue
85 }
86
87 dsa.P = p
88 dsa.Q = q
89 break GPLoop
90 }
91 }
92
93 // 4. Choose an integer h randomly from the range [2, p-2]. Commonly, h = 2
94 // 5. Compute g = h^((p-1)/q) mod p. In case g == 1, increment h until g != 1
95 pm1 := new(big.Int).Sub(p, one)
96
97 for g.Cmp(one) == 0 {
98 g.Exp(h, new(big.Int).Div(pm1, q), p)
99 h.Add(h, one)
100 }
101
102 dsa.G = g
103}
104
105// keyGen is key generation for DSA
106// 1. Choose a random integer x from the range [1, q-1]

Callers 1

NewFunction · 0.80

Calls 1

AddMethod · 0.65

Tested by

no test coverage detected