github.com/emmansun/gmsm@v0.29.1/sm9/sm9_key.go (about) 1 package sm9 2 3 import ( 4 "encoding/pem" 5 6 "errors" 7 "io" 8 "math/big" 9 "sync" 10 11 "github.com/emmansun/gmsm/internal/bigmod" 12 "github.com/emmansun/gmsm/sm9/bn256" 13 "golang.org/x/crypto/cryptobyte" 14 cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1" 15 ) 16 17 // SignMasterPrivateKey master private key for sign, generated by KGC 18 type SignMasterPrivateKey struct { 19 *SignMasterPublicKey // master public key 20 D *big.Int // master private key 21 } 22 23 // SignMasterPublicKey master public key for sign, generated by KGC 24 type SignMasterPublicKey struct { 25 MasterPublicKey *bn256.G2 // master public key 26 pairOnce sync.Once 27 basePoint *bn256.GT // the result of Pair(Gen1, pub.MasterPublicKey) 28 tableGenOnce sync.Once 29 table *[32 * 2]bn256.GTFieldTable // precomputed basePoint^n 30 } 31 32 // SignPrivateKey user private key for sign, generated by KGC 33 type SignPrivateKey struct { 34 PrivateKey *bn256.G1 // user private key 35 *SignMasterPublicKey // master public key 36 } 37 38 // EncryptMasterPrivateKey master private key for encryption, generated by KGC 39 type EncryptMasterPrivateKey struct { 40 *EncryptMasterPublicKey // master public key 41 D *big.Int // master private key 42 } 43 44 // EncryptMasterPublicKey master private key for encryption, generated by KGC 45 type EncryptMasterPublicKey struct { 46 MasterPublicKey *bn256.G1 // public key 47 pairOnce sync.Once 48 basePoint *bn256.GT // the result of Pair(pub.MasterPublicKey, Gen2) 49 tableGenOnce sync.Once 50 table *[32 * 2]bn256.GTFieldTable // precomputed basePoint^n 51 } 52 53 // EncryptPrivateKey user private key for encryption, generated by KGC 54 type EncryptPrivateKey struct { 55 PrivateKey *bn256.G2 // user private key 56 *EncryptMasterPublicKey // master public key 57 } 58 59 // GenerateSignMasterKey generates a master public and private key pair for DSA usage. 60 func GenerateSignMasterKey(rand io.Reader) (*SignMasterPrivateKey, error) { 61 k, err := randomScalar(rand) 62 if err != nil { 63 return nil, err 64 } 65 kBytes := k.Bytes(orderNat) 66 p, err := new(bn256.G2).ScalarBaseMult(kBytes) 67 if err != nil { 68 return nil, err 69 } 70 71 priv := new(SignMasterPrivateKey) 72 priv.D = new(big.Int).SetBytes(kBytes) 73 priv.SignMasterPublicKey = new(SignMasterPublicKey) 74 priv.MasterPublicKey = p 75 return priv, nil 76 } 77 78 // MarshalASN1 marshal sign master private key to asn.1 format data according 79 // SM9 cryptographic algorithm application specification 80 func (master *SignMasterPrivateKey) MarshalASN1() ([]byte, error) { 81 var b cryptobyte.Builder 82 b.AddASN1BigInt(master.D) 83 return b.Bytes() 84 } 85 86 // UnmarshalASN1 unmarsal der data to sign master private key 87 func (master *SignMasterPrivateKey) UnmarshalASN1(der []byte) error { 88 input := cryptobyte.String(der) 89 d := &big.Int{} 90 var inner cryptobyte.String 91 var pubBytes []byte 92 if der[0] == 0x30 { 93 if !input.ReadASN1(&inner, cryptobyte_asn1.SEQUENCE) || 94 !input.Empty() || 95 !inner.ReadASN1Integer(d) { 96 return errors.New("sm9: invalid sign master private key asn1 data") 97 } 98 // Just parse it, did't validate it 99 if !inner.Empty() && (!inner.ReadASN1BitStringAsBytes(&pubBytes) || !inner.Empty()) { 100 return errors.New("sm9: invalid sign master public key asn1 data") 101 } 102 } else if !input.ReadASN1Integer(d) || !input.Empty() { 103 return errors.New("sm9: invalid sign master private key asn1 data") 104 } 105 master.D = d 106 master.SignMasterPublicKey = new(SignMasterPublicKey) 107 p, err := new(bn256.G2).ScalarBaseMult(bn256.NormalizeScalar(d.Bytes())) 108 if err != nil { 109 return err 110 } 111 master.MasterPublicKey = p 112 return nil 113 } 114 115 // GenerateUserKey generate an user dsa key. 116 func (master *SignMasterPrivateKey) GenerateUserKey(uid []byte, hid byte) (*SignPrivateKey, error) { 117 var id []byte 118 id = append(id, uid...) 119 id = append(id, hid) 120 121 t1Nat := hashH1(id) 122 123 d, err := bigmod.NewNat().SetBytes(master.D.Bytes(), orderNat) 124 if err != nil { 125 return nil, err 126 } 127 128 t1Nat.Add(d, orderNat) 129 if t1Nat.IsZero() == 1 { 130 return nil, errors.New("sm9: need to re-generate sign master private key") 131 } 132 133 t1Nat = bigmod.NewNat().Exp(t1Nat, orderMinus2, orderNat) 134 t1Nat.Mul(d, orderNat) 135 136 priv := new(SignPrivateKey) 137 priv.SignMasterPublicKey = master.SignMasterPublicKey 138 g1, err := new(bn256.G1).ScalarBaseMult(t1Nat.Bytes(orderNat)) 139 if err != nil { 140 return nil, err 141 } 142 priv.PrivateKey = g1 143 144 return priv, nil 145 } 146 147 // Public returns the public key corresponding to priv. 148 func (master *SignMasterPrivateKey) Public() *SignMasterPublicKey { 149 return master.SignMasterPublicKey 150 } 151 152 // pair generate the basepoint once 153 func (pub *SignMasterPublicKey) pair() *bn256.GT { 154 pub.pairOnce.Do(func() { 155 pub.basePoint = bn256.Pair(bn256.Gen1, pub.MasterPublicKey) 156 }) 157 return pub.basePoint 158 } 159 160 func (pub *SignMasterPublicKey) generatorTable() *[32 * 2]bn256.GTFieldTable { 161 pub.tableGenOnce.Do(func() { 162 pub.table = bn256.GenerateGTFieldTable(pub.pair()) 163 }) 164 return pub.table 165 } 166 167 // ScalarBaseMult compute basepoint^r with precomputed table 168 // The base point = pair(Gen1, <master public key>) 169 func (pub *SignMasterPublicKey) ScalarBaseMult(scalar []byte) (*bn256.GT, error) { 170 tables := pub.generatorTable() 171 return bn256.ScalarBaseMultGT(tables, scalar) 172 } 173 174 // GenerateUserPublicKey generate user sign public key 175 func (pub *SignMasterPublicKey) GenerateUserPublicKey(uid []byte, hid byte) *bn256.G2 { 176 var buffer []byte 177 buffer = append(buffer, uid...) 178 buffer = append(buffer, hid) 179 h1 := hashH1(buffer) 180 p, err := new(bn256.G2).ScalarBaseMult(h1.Bytes(orderNat)) 181 if err != nil { 182 panic(err) 183 } 184 p.Add(p, pub.MasterPublicKey) 185 return p 186 } 187 188 // MarshalASN1 marshal sign master public key to asn.1 format data according 189 // SM9 cryptographic algorithm application specification 190 func (pub *SignMasterPublicKey) MarshalASN1() ([]byte, error) { 191 var b cryptobyte.Builder 192 b.AddASN1BitString(pub.MasterPublicKey.MarshalUncompressed()) 193 return b.Bytes() 194 } 195 196 // MarshalCompressedASN1 marshal sign master public key to asn.1 format data according 197 // SM9 cryptographic algorithm application specification, the curve point is in compressed form. 198 func (pub *SignMasterPublicKey) MarshalCompressedASN1() ([]byte, error) { 199 var b cryptobyte.Builder 200 b.AddASN1BitString(pub.MasterPublicKey.MarshalCompressed()) 201 return b.Bytes() 202 } 203 204 func unmarshalG2(bytes []byte) (*bn256.G2, error) { 205 g2 := new(bn256.G2) 206 switch bytes[0] { 207 case 4: 208 _, err := g2.Unmarshal(bytes[1:]) 209 if err != nil { 210 return nil, err 211 } 212 case 2, 3: 213 _, err := g2.UnmarshalCompressed(bytes) 214 if err != nil { 215 return nil, err 216 } 217 default: 218 return nil, errors.New("sm9: invalid point identity byte") 219 } 220 return g2, nil 221 } 222 223 // UnmarshalRaw unmarsal raw bytes data to sign master public key 224 func (pub *SignMasterPublicKey) UnmarshalRaw(bytes []byte) error { 225 g2, err := unmarshalG2(bytes) 226 if err != nil { 227 return err 228 } 229 pub.MasterPublicKey = g2 230 return nil 231 } 232 233 // UnmarshalASN1 unmarsal der data to sign master public key 234 func (pub *SignMasterPublicKey) UnmarshalASN1(der []byte) error { 235 var bytes []byte 236 var inner cryptobyte.String 237 input := cryptobyte.String(der) 238 if der[0] == 0x30 { 239 if !input.ReadASN1(&inner, cryptobyte_asn1.SEQUENCE) || 240 !input.Empty() || 241 !inner.ReadASN1BitStringAsBytes(&bytes) || 242 !inner.Empty() { 243 return errors.New("sm9: invalid sign master public key asn1 data") 244 } 245 } else if !input.ReadASN1BitStringAsBytes(&bytes) || !input.Empty() { 246 return errors.New("sm9: invalid sign master public key asn1 data") 247 } 248 return pub.UnmarshalRaw(bytes) 249 } 250 251 // ParseFromPEM just for GMSSL, there are no Algorithm pkix.AlgorithmIdentifier 252 func (pub *SignMasterPublicKey) ParseFromPEM(data []byte) error { 253 block, _ := pem.Decode([]byte(data)) 254 if block == nil { 255 return errors.New("sm9: failed to parse PEM block") 256 } 257 return pub.UnmarshalASN1(block.Bytes) 258 } 259 260 // MasterPublic returns the master public key corresponding to priv. 261 func (priv *SignPrivateKey) MasterPublic() *SignMasterPublicKey { 262 return priv.SignMasterPublicKey 263 } 264 265 // SetMasterPublicKey bind the sign master public key to it. 266 func (priv *SignPrivateKey) SetMasterPublicKey(pub *SignMasterPublicKey) { 267 if priv.SignMasterPublicKey == nil || priv.SignMasterPublicKey.MasterPublicKey == nil { 268 priv.SignMasterPublicKey = pub 269 } 270 } 271 272 // MarshalASN1 marshal sign user private key to asn.1 format data according 273 // SM9 cryptographic algorithm application specification 274 func (priv *SignPrivateKey) MarshalASN1() ([]byte, error) { 275 var b cryptobyte.Builder 276 b.AddASN1BitString(priv.PrivateKey.MarshalUncompressed()) 277 return b.Bytes() 278 } 279 280 // MarshalCompressedASN1 marshal sign user private key to asn.1 format data according 281 // SM9 cryptographic algorithm application specification, the curve point is in compressed form. 282 func (priv *SignPrivateKey) MarshalCompressedASN1() ([]byte, error) { 283 var b cryptobyte.Builder 284 b.AddASN1BitString(priv.PrivateKey.MarshalCompressed()) 285 return b.Bytes() 286 } 287 288 func unmarshalG1(bytes []byte) (*bn256.G1, error) { 289 g := new(bn256.G1) 290 switch bytes[0] { 291 case 4: 292 _, err := g.Unmarshal(bytes[1:]) 293 if err != nil { 294 return nil, err 295 } 296 case 2, 3: 297 _, err := g.UnmarshalCompressed(bytes) 298 if err != nil { 299 return nil, err 300 } 301 default: 302 return nil, errors.New("sm9: invalid point identity byte") 303 } 304 return g, nil 305 } 306 307 // UnmarshalRaw unmarsal raw bytes data to sign user private key 308 // Note, priv's SignMasterPublicKey should be handled separately. 309 func (priv *SignPrivateKey) UnmarshalRaw(bytes []byte) error { 310 g, err := unmarshalG1(bytes) 311 if err != nil { 312 return err 313 } 314 priv.PrivateKey = g 315 return nil 316 } 317 318 // UnmarshalASN1 unmarsal der data to sign user private key 319 // Note, priv's SignMasterPublicKey should be handled separately. 320 func (priv *SignPrivateKey) UnmarshalASN1(der []byte) error { 321 var bytes []byte 322 var pubBytes []byte 323 var inner cryptobyte.String 324 input := cryptobyte.String(der) 325 if der[0] == 0x30 { 326 if !input.ReadASN1(&inner, cryptobyte_asn1.SEQUENCE) || 327 !input.Empty() || 328 !inner.ReadASN1BitStringAsBytes(&bytes) { 329 return errors.New("sm9: invalid sign user private key asn1 data") 330 } 331 if !inner.Empty() && (!inner.ReadASN1BitStringAsBytes(&pubBytes) || !inner.Empty()) { 332 return errors.New("sm9: invalid sign master public key asn1 data") 333 } 334 } else if !input.ReadASN1BitStringAsBytes(&bytes) || !input.Empty() { 335 return errors.New("sm9: invalid sign user private key asn1 data") 336 } 337 err := priv.UnmarshalRaw(bytes) 338 if err != nil { 339 return err 340 } 341 if len(pubBytes) > 0 { 342 masterPK := new(SignMasterPublicKey) 343 err = masterPK.UnmarshalRaw(pubBytes) 344 if err != nil { 345 return err 346 } 347 priv.SetMasterPublicKey(masterPK) 348 } 349 return nil 350 } 351 352 // GenerateEncryptMasterKey generates a master public and private key pair for encryption usage. 353 func GenerateEncryptMasterKey(rand io.Reader) (*EncryptMasterPrivateKey, error) { 354 k, err := randomScalar(rand) 355 if err != nil { 356 return nil, err 357 } 358 kBytes := k.Bytes(orderNat) 359 360 priv := new(EncryptMasterPrivateKey) 361 priv.D = new(big.Int).SetBytes(kBytes) 362 priv.EncryptMasterPublicKey = new(EncryptMasterPublicKey) 363 p, err := new(bn256.G1).ScalarBaseMult(kBytes) 364 if err != nil { 365 panic(err) 366 } 367 priv.MasterPublicKey = p 368 return priv, nil 369 } 370 371 // GenerateUserKey generate an user key for encryption. 372 func (master *EncryptMasterPrivateKey) GenerateUserKey(uid []byte, hid byte) (*EncryptPrivateKey, error) { 373 var id []byte 374 id = append(id, uid...) 375 id = append(id, hid) 376 377 t1Nat := hashH1(id) 378 379 d, err := bigmod.NewNat().SetBytes(master.D.Bytes(), orderNat) 380 if err != nil { 381 return nil, err 382 } 383 384 t1Nat.Add(d, orderNat) 385 if t1Nat.IsZero() == 1 { 386 return nil, errors.New("sm9: need to re-generate encrypt master private key") 387 } 388 389 t1Nat = bigmod.NewNat().Exp(t1Nat, orderMinus2, orderNat) 390 t1Nat.Mul(d, orderNat) 391 392 priv := new(EncryptPrivateKey) 393 priv.EncryptMasterPublicKey = master.EncryptMasterPublicKey 394 p, err := new(bn256.G2).ScalarBaseMult(t1Nat.Bytes(orderNat)) 395 if err != nil { 396 panic(err) 397 } 398 priv.PrivateKey = p 399 400 return priv, nil 401 } 402 403 // Public returns the public key corresponding to priv. 404 func (master *EncryptMasterPrivateKey) Public() *EncryptMasterPublicKey { 405 return master.EncryptMasterPublicKey 406 } 407 408 // MarshalASN1 marshal encrypt master private key to asn.1 format data according 409 // SM9 cryptographic algorithm application specification 410 func (master *EncryptMasterPrivateKey) MarshalASN1() ([]byte, error) { 411 var b cryptobyte.Builder 412 b.AddASN1BigInt(master.D) 413 return b.Bytes() 414 } 415 416 // UnmarshalASN1 unmarsal der data to encrypt master private key 417 func (master *EncryptMasterPrivateKey) UnmarshalASN1(der []byte) error { 418 input := cryptobyte.String(der) 419 d := &big.Int{} 420 var inner cryptobyte.String 421 var pubBytes []byte 422 if der[0] == 0x30 { 423 if !input.ReadASN1(&inner, cryptobyte_asn1.SEQUENCE) || 424 !input.Empty() || 425 !inner.ReadASN1Integer(d) { 426 return errors.New("sm9: invalid encrypt master private key asn1 data") 427 } 428 // Just parse it, did't validate it 429 if !inner.Empty() && (!inner.ReadASN1BitStringAsBytes(&pubBytes) || !inner.Empty()) { 430 return errors.New("sm9: invalid encrypt master public key asn1 data") 431 } 432 } else if !input.ReadASN1Integer(d) || !input.Empty() { 433 return errors.New("sm9: invalid encrypt master private key asn1 data") 434 } 435 master.D = d 436 master.EncryptMasterPublicKey = new(EncryptMasterPublicKey) 437 p, err := new(bn256.G1).ScalarBaseMult(bn256.NormalizeScalar(d.Bytes())) 438 if err != nil { 439 return err 440 } 441 master.MasterPublicKey = p 442 return nil 443 } 444 445 // pair generate the basepoint once 446 func (pub *EncryptMasterPublicKey) pair() *bn256.GT { 447 pub.pairOnce.Do(func() { 448 pub.basePoint = bn256.Pair(pub.MasterPublicKey, bn256.Gen2) 449 }) 450 return pub.basePoint 451 } 452 453 func (pub *EncryptMasterPublicKey) generatorTable() *[32 * 2]bn256.GTFieldTable { 454 pub.tableGenOnce.Do(func() { 455 pub.table = bn256.GenerateGTFieldTable(pub.pair()) 456 }) 457 return pub.table 458 } 459 460 // ScalarBaseMult compute basepoint^r with precomputed table. 461 // The base point = pair(<master public key>, Gen2) 462 func (pub *EncryptMasterPublicKey) ScalarBaseMult(scalar []byte) (*bn256.GT, error) { 463 tables := pub.generatorTable() 464 return bn256.ScalarBaseMultGT(tables, scalar) 465 } 466 467 // GenerateUserPublicKey generate user encrypt public key 468 func (pub *EncryptMasterPublicKey) GenerateUserPublicKey(uid []byte, hid byte) *bn256.G1 { 469 var buffer []byte 470 buffer = append(buffer, uid...) 471 buffer = append(buffer, hid) 472 h1 := hashH1(buffer) 473 p, err := new(bn256.G1).ScalarBaseMult(h1.Bytes(orderNat)) 474 if err != nil { 475 panic(err) 476 } 477 p.Add(p, pub.MasterPublicKey) 478 return p 479 } 480 481 // MarshalASN1 marshal encrypt master public key to asn.1 format data according 482 // SM9 cryptographic algorithm application specification 483 func (pub *EncryptMasterPublicKey) MarshalASN1() ([]byte, error) { 484 var b cryptobyte.Builder 485 b.AddASN1BitString(pub.MasterPublicKey.MarshalUncompressed()) 486 return b.Bytes() 487 } 488 489 // MarshalCompressedASN1 marshal encrypt master public key to asn.1 format data according 490 // SM9 cryptographic algorithm application specification, the curve point is in compressed form. 491 func (pub *EncryptMasterPublicKey) MarshalCompressedASN1() ([]byte, error) { 492 var b cryptobyte.Builder 493 b.AddASN1BitString(pub.MasterPublicKey.MarshalCompressed()) 494 return b.Bytes() 495 } 496 497 // UnmarshalRaw unmarsal raw bytes data to encrypt master public key 498 func (pub *EncryptMasterPublicKey) UnmarshalRaw(bytes []byte) error { 499 g, err := unmarshalG1(bytes) 500 if err != nil { 501 return err 502 } 503 pub.MasterPublicKey = g 504 return nil 505 } 506 507 // ParseFromPEM just for GMSSL, there are no Algorithm pkix.AlgorithmIdentifier 508 func (pub *EncryptMasterPublicKey) ParseFromPEM(data []byte) error { 509 block, _ := pem.Decode([]byte(data)) 510 if block == nil { 511 return errors.New("sm9: failed to parse PEM block") 512 } 513 return pub.UnmarshalASN1(block.Bytes) 514 } 515 516 // UnmarshalASN1 unmarsal der data to encrypt master public key 517 func (pub *EncryptMasterPublicKey) UnmarshalASN1(der []byte) error { 518 var bytes []byte 519 var inner cryptobyte.String 520 input := cryptobyte.String(der) 521 if der[0] == 0x30 { 522 if !input.ReadASN1(&inner, cryptobyte_asn1.SEQUENCE) || 523 !input.Empty() || 524 !inner.ReadASN1BitStringAsBytes(&bytes) || 525 !inner.Empty() { 526 return errors.New("sm9: invalid encrypt master public key asn1 data") 527 } 528 } else if !input.ReadASN1BitStringAsBytes(&bytes) || !input.Empty() { 529 return errors.New("sm9: invalid encrypt master public key asn1 data") 530 } 531 return pub.UnmarshalRaw(bytes) 532 } 533 534 // MasterPublic returns the master public key corresponding to priv. 535 func (priv *EncryptPrivateKey) MasterPublic() *EncryptMasterPublicKey { 536 return priv.EncryptMasterPublicKey 537 } 538 539 // SetMasterPublicKey bind the encrypt master public key to it. 540 func (priv *EncryptPrivateKey) SetMasterPublicKey(pub *EncryptMasterPublicKey) { 541 if priv.EncryptMasterPublicKey == nil || priv.EncryptMasterPublicKey.MasterPublicKey == nil { 542 priv.EncryptMasterPublicKey = pub 543 } 544 } 545 546 // MarshalASN1 marshal encrypt user private key to asn.1 format data according 547 // SM9 cryptographic algorithm application specification 548 func (priv *EncryptPrivateKey) MarshalASN1() ([]byte, error) { 549 var b cryptobyte.Builder 550 b.AddASN1BitString(priv.PrivateKey.MarshalUncompressed()) 551 return b.Bytes() 552 } 553 554 // MarshalCompressedASN1 marshal encrypt user private key to asn.1 format data according 555 // SM9 cryptographic algorithm application specification, the curve point is in compressed form. 556 func (priv *EncryptPrivateKey) MarshalCompressedASN1() ([]byte, error) { 557 var b cryptobyte.Builder 558 b.AddASN1BitString(priv.PrivateKey.MarshalCompressed()) 559 return b.Bytes() 560 } 561 562 // UnmarshalRaw unmarsal raw bytes data to encrypt user private key 563 // Note, priv's EncryptMasterPublicKey should be handled separately. 564 func (priv *EncryptPrivateKey) UnmarshalRaw(bytes []byte) error { 565 g, err := unmarshalG2(bytes) 566 if err != nil { 567 return err 568 } 569 priv.PrivateKey = g 570 return nil 571 } 572 573 // UnmarshalASN1 unmarsal der data to encrypt user private key 574 // Note, priv's EncryptMasterPublicKey should be handled separately. 575 func (priv *EncryptPrivateKey) UnmarshalASN1(der []byte) error { 576 var bytes []byte 577 var pubBytes []byte 578 var inner cryptobyte.String 579 input := cryptobyte.String(der) 580 if der[0] == 0x30 { 581 if !input.ReadASN1(&inner, cryptobyte_asn1.SEQUENCE) || 582 !input.Empty() || 583 !inner.ReadASN1BitStringAsBytes(&bytes) { 584 return errors.New("sm9: invalid encrypt user private key asn1 data") 585 } 586 if !inner.Empty() && (!inner.ReadASN1BitStringAsBytes(&pubBytes) || !inner.Empty()) { 587 return errors.New("sm9: invalid encrypt master public key asn1 data") 588 } 589 } else if !input.ReadASN1BitStringAsBytes(&bytes) || !input.Empty() { 590 return errors.New("sm9: invalid encrypt user private key asn1 data") 591 } 592 err := priv.UnmarshalRaw(bytes) 593 if err != nil { 594 return err 595 } 596 if len(pubBytes) > 0 { 597 masterPK := new(EncryptMasterPublicKey) 598 err = masterPK.UnmarshalRaw(pubBytes) 599 if err != nil { 600 return err 601 } 602 priv.SetMasterPublicKey(masterPK) 603 } 604 return nil 605 }