-
Notifications
You must be signed in to change notification settings - Fork 2
/
keys.go
418 lines (356 loc) · 10.9 KB
/
keys.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// Copyright 2016 Maarten Everts. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gabi
import (
"crypto/rand"
"encoding/xml"
"io"
"io/ioutil"
"math/big"
"os"
"strconv"
"time"
"errors"
"github.com/credentials/safeprime"
)
const (
//XMLHeader can be a used as the XML header when writing keys in XML format.
XMLHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
// DefaultEpochLength is the default epoch length for public keys.
DefaultEpochLength = 432000
)
// PrivateKey represents an issuer's private key.
type PrivateKey struct {
XMLName xml.Name `xml:"http://www.zurich.ibm.com/security/idemix IssuerPrivateKey"`
Counter uint `xml:"Counter"`
ExpiryDate int64 `xml:"ExpiryDate"`
P *big.Int `xml:"Elements>p"`
Q *big.Int `xml:"Elements>q"`
PPrime *big.Int `xml:"Elements>pPrime"`
QPrime *big.Int `xml:"Elements>qPrime"`
}
// NewPrivateKey creates a new issuer private key using the provided parameters.
func NewPrivateKey(p, q *big.Int, counter uint, expiryDate time.Time) *PrivateKey {
sk := PrivateKey{P: p, Q: q, PPrime: new(big.Int), QPrime: new(big.Int), Counter: counter, ExpiryDate: expiryDate.Unix()}
sk.PPrime.Sub(p, bigONE)
sk.PPrime.Rsh(sk.PPrime, 1)
sk.QPrime.Sub(q, bigONE)
sk.QPrime.Rsh(sk.QPrime, 1)
return &sk
}
// NewPrivateKeyFromXML creates a new issuer private key using the xml data
// provided.
func NewPrivateKeyFromXML(xmlInput string) (*PrivateKey, error) {
privk := &PrivateKey{}
err := xml.Unmarshal([]byte(xmlInput), privk)
if err != nil {
return nil, err
}
return privk, nil
}
// NewPrivateKeyFromFile create a new issuer private key from an xml file.
func NewPrivateKeyFromFile(filename string) (*PrivateKey, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
privk := &PrivateKey{}
b, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
err = xml.Unmarshal(b, privk)
if err != nil {
return nil, err
}
return privk, nil
}
// Print prints the key to stdout.
func (privk *PrivateKey) Print() error {
_, err := privk.WriteTo(os.Stdout)
return err
}
// WriteTo writes the XML-serialized public key to the given writer.
func (privk *PrivateKey) WriteTo(writer io.Writer) (int64, error) {
// Write the standard XML header
numHeaderBytes, err := writer.Write([]byte(XMLHeader))
if err != nil {
return 0, err
}
// And the actual xml body (with indentation)
b, err := xml.MarshalIndent(privk, "", " ")
if err != nil {
return int64(numHeaderBytes), err
}
numBodyBytes, err := writer.Write(b)
return int64(numHeaderBytes + numBodyBytes), err
}
// WriteToFile writes the private key to an xml file. If any existing file with
// the same filename should be overwritten, set forceOverwrite to true.
func (privk *PrivateKey) WriteToFile(filename string, forceOverwrite bool) (int64, error) {
var f *os.File
var err error
if forceOverwrite {
f, err = os.Create(filename)
} else {
// This should return an error if the file already exists
f, err = os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
}
if err != nil {
return 0, err
}
defer f.Close()
return privk.WriteTo(f)
}
// xmlBases is an auxiliary struct to encode/decode the odd way bases are
// represented in the xml representation of public keys
type xmlBases struct {
Num int `xml:"num,attr"`
Bases []*xmlBase `xml:",any"`
}
type xmlBase struct {
XMLName xml.Name
Bigint string `xml:",innerxml"` // Has to be a string for ",innerxml" to work
}
// xmlFeatures is an auxiliary struct to make the XML encoding/decoding a bit
// easier while keeping the struct for PublicKey somewhat simple.
type xmlFeatures struct {
Epoch struct {
Length int `xml:"length,attr"`
}
}
// Bases is a type that is introduced to simplify the encoding/decoding of
// a PublicKey whilst using the xml support of Go's standard library.
type Bases []*big.Int
// UnmarshalXML is an internal function to simplify decoding a PublicKey from
// XML.
func (bl *Bases) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var t xmlBases
if err := d.DecodeElement(&t, &start); err != nil {
return err
}
arr := make([]*big.Int, t.Num)
for i := range arr {
arr[i], _ = new(big.Int).SetString(t.Bases[i].Bigint, 10)
}
*bl = Bases(arr)
return nil
}
// MarshalXML is an internal function to simplify encoding a PublicKey to XML.
func (bl *Bases) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
l := len(*bl)
bases := make([]*xmlBase, l)
for i := range bases {
bases[i] = &xmlBase{
XMLName: xml.Name{Local: "Base_" + strconv.Itoa(i)},
Bigint: (*bl)[i].String(),
}
}
t := xmlBases{
Num: l,
Bases: bases,
}
return e.EncodeElement(t, start)
}
// EpochLength is a type that is introduced to simplify the encoding/decoding of
// a PublicKey whilst using the xml support of Go's standard library.
type EpochLength int
// UnmarshalXML is an internal function to simplify decoding a PublicKey from
// XML.
func (el *EpochLength) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var t xmlFeatures
if err := d.DecodeElement(&t, &start); err != nil {
return err
}
*el = EpochLength(t.Epoch.Length)
return nil
}
// MarshalXML is an internal function to simplify encoding a PublicKey to XML.
func (el *EpochLength) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
var t xmlFeatures
t.Epoch.Length = int(*el)
return e.EncodeElement(t, start)
}
// PublicKey represents an issuer's public key.
type PublicKey struct {
XMLName xml.Name `xml:"http://www.zurich.ibm.com/security/idemix IssuerPublicKey"`
Counter uint `xml:"Counter"`
ExpiryDate int64 `xml:"ExpiryDate"`
N *big.Int `xml:"Elements>n"` // Modulus n
Z *big.Int `xml:"Elements>Z"` // Generator Z
S *big.Int `xml:"Elements>S"` // Generator S
R Bases `xml:"Elements>Bases"`
EpochLength EpochLength `xml:"Features"`
Params *SystemParameters `xml:"-"`
Issuer string `xml:"-"`
}
// NewPublicKey creates and returns a new public key based on the provided parameters.
func NewPublicKey(N, Z, S *big.Int, R []*big.Int, counter uint, expiryDate time.Time) *PublicKey {
return &PublicKey{
Counter: counter,
ExpiryDate: expiryDate.Unix(),
N: N,
Z: Z,
S: S,
R: R,
EpochLength: DefaultEpochLength,
Params: DefaultSystemParameters[N.BitLen()],
}
}
// NewPublicKeyFromXML creates a new issuer public key using the xml data
// provided.
func NewPublicKeyFromBytes(bts []byte) (*PublicKey, error) {
// TODO: this might fail in the future. The DefaultSystemParameters and the
// public key might not match!
pubk := &PublicKey{}
err := xml.Unmarshal(bts, pubk)
if err != nil {
return nil, err
}
keylength := pubk.N.BitLen()
if sysparam, ok := DefaultSystemParameters[keylength]; ok {
pubk.Params = sysparam
} else {
return nil, errors.New("Unknown keylength")
}
return pubk, nil
}
func NewPublicKeyFromXML(xmlInput string) (*PublicKey, error) {
return NewPublicKeyFromBytes([]byte(xmlInput))
}
// NewPublicKeyFromFile create a new issuer public key from an xml file.
func NewPublicKeyFromFile(filename string) (*PublicKey, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
pubk := &PublicKey{}
b, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
err = xml.Unmarshal(b, pubk)
if err != nil {
return nil, err
}
pubk.Params = DefaultSystemParameters[pubk.N.BitLen()]
return pubk, nil
}
// Print prints the key to stdout.
func (pubk *PublicKey) Print() error {
_, err := pubk.WriteTo(os.Stdout)
return err
}
// WriteTo writes the XML-serialized public key to the given writer.
func (pubk *PublicKey) WriteTo(writer io.Writer) (int64, error) {
// Write the standard XML header
numHeaderBytes, err := writer.Write([]byte(XMLHeader))
if err != nil {
return 0, err
}
// And the actual xml body (with indentation)
b, err := xml.MarshalIndent(pubk, "", " ")
if err != nil {
return int64(numHeaderBytes), err
}
numBodyBytes, err := writer.Write(b)
return int64(numHeaderBytes + numBodyBytes), err
}
// WriteToFile writes the public key to an xml file. If any existing file with
// the same filename should be overwritten, set forceOverwrite to true.
func (pubk *PublicKey) WriteToFile(filename string, forceOverwrite bool) (int64, error) {
var f *os.File
var err error
if forceOverwrite {
f, err = os.Create(filename)
} else {
// This should return an error if the file already exists
f, err = os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
}
if err != nil {
return 0, err
}
defer f.Close()
return pubk.WriteTo(f)
}
// randomSafePrime produces a safe prime of the requested number of bits
func randomSafePrime(bits int) (*big.Int, error) {
p2 := new(big.Int)
for {
p, err := rand.Prime(rand.Reader, bits)
if err != nil {
return nil, err
}
p2.Rsh(p, 1) // p2 = (p - 1)/2
if p2.ProbablyPrime(20) {
return p, nil
}
}
}
// GenerateKeyPair generates a private/public keypair for an Issuer
func GenerateKeyPair(param *SystemParameters, numAttributes int, counter uint, expiryDate time.Time) (*PrivateKey, *PublicKey, error) {
primeSize := param.Ln / 2
// p and q need to be safe primes
p, err := safeprime.Generate(int(primeSize))
if err != nil {
return nil, nil, err
}
q, err := safeprime.Generate(int(primeSize))
if err != nil {
return nil, nil, err
}
priv := &PrivateKey{P: p, Q: q, PPrime: new(big.Int), QPrime: new(big.Int), Counter: counter, ExpiryDate: expiryDate.Unix()}
// compute p' and q'
priv.PPrime.Sub(priv.P, bigONE)
priv.PPrime.Rsh(priv.PPrime, 1)
priv.QPrime.Sub(priv.Q, bigONE)
priv.QPrime.Rsh(priv.QPrime, 1)
// compute n
pubk := &PublicKey{Params: param, EpochLength: DefaultEpochLength, Counter: counter, ExpiryDate: expiryDate.Unix()}
pubk.N = new(big.Int).Mul(priv.P, priv.Q)
// Find an acceptable value for S; we follow lead of the Silvia code here:
// Pick a random l_n value and check whether it is a quadratic residue modulo n
var s *big.Int
for {
s, err = RandomBigInt(param.Ln)
if err != nil {
return nil, nil, err
}
// check if S \elem Z_n
if s.Cmp(pubk.N) > 0 {
continue
}
if legendreSymbol(s, priv.P) == 1 && legendreSymbol(s, priv.Q) == 1 {
break
}
}
pubk.S = s
// Derive Z from S
var x *big.Int
for {
x, _ = RandomBigInt(primeSize)
if x.Cmp(bigTWO) > 0 && x.Cmp(pubk.N) < 0 {
break
}
}
// Compute Z = S^x mod n
pubk.Z = new(big.Int).Exp(pubk.S, x, pubk.N)
// Derive R_i for i = 0...numAttributes from S
pubk.R = make([]*big.Int, numAttributes)
for i := 0; i < numAttributes; i++ {
pubk.R[i] = new(big.Int)
var x *big.Int
for {
x, _ = RandomBigInt(primeSize)
if x.Cmp(bigTWO) > 0 && x.Cmp(pubk.N) < 0 {
break
}
}
// Compute R_i = S^x mod n
pubk.R[i].Exp(pubk.S, x, pubk.N)
}
return priv, pubk, nil
}