...
Source file src/pkg/crypto/rand/util.go
1
2
3
4
5 package rand
6
7 import (
8 "errors"
9 "io"
10 "math/big"
11 )
12
13
14
15
16
17
18 var smallPrimes = []uint8{
19 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53,
20 }
21
22
23
24
25
26 var smallPrimesProduct = new(big.Int).SetUint64(16294579238595022365)
27
28
29
30
31 func Prime(rand io.Reader, bits int) (p *big.Int, err error) {
32 if bits < 2 {
33 err = errors.New("crypto/rand: prime size must be at least 2-bit")
34 return
35 }
36
37 b := uint(bits % 8)
38 if b == 0 {
39 b = 8
40 }
41
42 bytes := make([]byte, (bits+7)/8)
43 p = new(big.Int)
44
45 bigMod := new(big.Int)
46
47 for {
48 _, err = io.ReadFull(rand, bytes)
49 if err != nil {
50 return nil, err
51 }
52
53
54 bytes[0] &= uint8(int(1<<b) - 1)
55
56
57
58
59 if b >= 2 {
60 bytes[0] |= 3 << (b - 2)
61 } else {
62
63 bytes[0] |= 1
64 if len(bytes) > 1 {
65 bytes[1] |= 0x80
66 }
67 }
68
69 bytes[len(bytes)-1] |= 1
70
71 p.SetBytes(bytes)
72
73
74
75
76
77 bigMod.Mod(p, smallPrimesProduct)
78 mod := bigMod.Uint64()
79
80 NextDelta:
81 for delta := uint64(0); delta < 1<<20; delta += 2 {
82 m := mod + delta
83 for _, prime := range smallPrimes {
84 if m%uint64(prime) == 0 && (bits > 6 || m != uint64(prime)) {
85 continue NextDelta
86 }
87 }
88
89 if delta > 0 {
90 bigMod.SetUint64(delta)
91 p.Add(p, bigMod)
92 }
93 break
94 }
95
96
97
98
99 if p.ProbablyPrime(20) && p.BitLen() == bits {
100 return
101 }
102 }
103 }
104
105
106 func Int(rand io.Reader, max *big.Int) (n *big.Int, err error) {
107 if max.Sign() <= 0 {
108 panic("crypto/rand: argument to Int is <= 0")
109 }
110 n = new(big.Int)
111 n.Sub(max, n.SetUint64(1))
112
113 bitLen := n.BitLen()
114 if bitLen == 0 {
115
116 return
117 }
118
119 k := (bitLen + 7) / 8
120
121 b := uint(bitLen % 8)
122 if b == 0 {
123 b = 8
124 }
125
126 bytes := make([]byte, k)
127
128 for {
129 _, err = io.ReadFull(rand, bytes)
130 if err != nil {
131 return nil, err
132 }
133
134
135
136 bytes[0] &= uint8(int(1<<b) - 1)
137
138 n.SetBytes(bytes)
139 if n.Cmp(max) < 0 {
140 return
141 }
142 }
143 }
144
View as plain text