github.com/klaytn/klaytn@v1.12.1/crypto/bls/blst/secret_key.go (about)

     1  // Copyright 2023 The klaytn Authors
     2  // This file is part of the klaytn library.
     3  //
     4  // The klaytn library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The klaytn library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the klaytn library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package blst
    18  
    19  import (
    20  	"crypto/rand"
    21  
    22  	"github.com/klaytn/klaytn/crypto/bls/types"
    23  	blst "github.com/supranational/blst/bindings/go"
    24  )
    25  
    26  type secretKey struct {
    27  	// Pointer to underlying blst struct, hence the name 'p'
    28  	p *blstSecretKey
    29  }
    30  
    31  func GenerateKey(ikm []byte) (types.SecretKey, error) {
    32  	// draft-irtf-cfrg-bls-signature-05 section 2.3. KeyGen
    33  	// requires that IKM MUST be at least 32 bytes long, but it MAY be longer.
    34  	if len(ikm) < 32 {
    35  		return nil, types.ErrSecretKeyGen
    36  	}
    37  
    38  	p := blst.KeyGen(ikm)
    39  	if p == nil || !p.Valid() {
    40  		return nil, types.ErrSecretKeyGen
    41  	}
    42  	return &secretKey{p: p}, nil
    43  }
    44  
    45  func RandKey() (types.SecretKey, error) {
    46  	ikm := make([]byte, 32)
    47  	if _, err := rand.Read(ikm); err != nil {
    48  		return nil, err
    49  	}
    50  	return GenerateKey(ikm)
    51  }
    52  
    53  func SecretKeyFromBytes(b []byte) (types.SecretKey, error) {
    54  	if len(b) != types.SecretKeyLength {
    55  		return nil, types.ErrSecretKeyLength(len(b))
    56  	}
    57  
    58  	p := new(blstSecretKey).Deserialize(b)
    59  	if p == nil || !p.Valid() {
    60  		return nil, types.ErrSecretKeyUnmarshal
    61  	}
    62  	return &secretKey{p: p}, nil
    63  }
    64  
    65  func (sk *secretKey) PublicKey() types.PublicKey {
    66  	// must succeed because SecretKey always hold a valid scalar,
    67  	p := new(blstPublicKey).From(sk.p) // blst_sk_to_pk2_in_g2
    68  	return &publicKey{p: p}
    69  }
    70  
    71  func (sk *secretKey) Marshal() []byte {
    72  	return sk.p.Serialize() // blst_p1_affine_serialize
    73  }