Skip to content

Commit

Permalink
add smcrypto.GenerateKey (#191)
Browse files Browse the repository at this point in the history
  • Loading branch information
bxq2011hust committed Feb 7, 2023
1 parent ff76ecf commit 16bfa5b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
19 changes: 19 additions & 0 deletions smcrypto/sm_crypto.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package smcrypto

import (
"crypto/rand"
"encoding/hex"
"encoding/pem"
"errors"
"fmt"
"io"
"math/big"

"github.com/FISCO-BCOS/crypto/ecdsa"
Expand Down Expand Up @@ -51,6 +53,23 @@ func SM2KeyToAddress(privateKey []byte) common.Address {
return common.BytesToAddress(sm3digest[12:])
}

var one = new(big.Int).SetInt64(1)

// GenerateKey generates a new private key.
func GenerateKey() (*ecdsa.PrivateKey, error) {
params := elliptic.Sm2p256v1().Params()
b := make([]byte, params.BitSize/8+8) // TODO: use params.N.BitLen()
_, err := io.ReadFull(rand.Reader, b)
if err != nil {
return nil, err
}
k := new(big.Int).SetBytes(b)
n := new(big.Int).Sub(params.N, one)
k.Mod(k, n)
k.Add(k, one)
return ToSM2(k.Bytes())
}

// ToSM2 creates a private key with the given D value.
func ToSM2(d []byte) (*ecdsa.PrivateKey, error) {
priv := new(ecdsa.PrivateKey)
Expand Down
1 change: 0 additions & 1 deletion smcrypto/sm_crypto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ func TestHexToSM2(t *testing.T) {
if pem != sm2pem {
t.Fatalf("pem mismatch, want: %s have: %s", sm2pem, pem)
}

}

// func TestSM2Sign(t *testing.T) {
Expand Down

0 comments on commit 16bfa5b

Please sign in to comment.