gitee.com/lh-her-team/common@v1.5.1/helper/libp2pcrypto/key_openssl.go (about) 1 // +build openssl 2 3 package libp2pcrypto 4 5 import ( 6 "crypto" 7 "crypto/ecdsa" 8 "crypto/ed25519" 9 "crypto/rsa" 10 "crypto/x509" 11 12 btcec "github.com/btcsuite/btcd/btcec" 13 openssl "github.com/libp2p/go-openssl" 14 "github.com/tjfoc/gmsm/sm2" 15 ) 16 17 // KeyPairFromStdKey wraps standard library (and secp256k1) private keys in libp2p/go-libp2p-core/crypto keys 18 func KeyPairFromStdKey(priv crypto.PrivateKey) (PrivKey, PubKey, error) { 19 if priv == nil { 20 return nil, nil, ErrNilPrivateKey 21 } 22 switch p := priv.(type) { 23 case *rsa.PrivateKey: 24 pk, err := openssl.LoadPrivateKeyFromDER(x509.MarshalPKCS1PrivateKey(p)) 25 if err != nil { 26 return nil, nil, err 27 } 28 return &opensslPrivateKey{pk}, &opensslPublicKey{key: pk}, nil 29 case *ecdsa.PrivateKey: 30 return &ECDSAPrivateKey{p}, &ECDSAPublicKey{&p.PublicKey}, nil 31 case *ed25519.PrivateKey: 32 pubIfc := p.Public() 33 pub, _ := pubIfc.(ed25519.PublicKey) 34 return &Ed25519PrivateKey{*p}, &Ed25519PublicKey{pub}, nil 35 case *btcec.PrivateKey: 36 sPriv := Secp256k1PrivateKey(*p) 37 sPub := Secp256k1PublicKey(*p.PubKey()) 38 return &sPriv, &sPub, nil 39 case *sm2.PrivateKey: 40 return &SM2PrivateKey{p}, &SM2PublicKey{&p.PublicKey}, nil 41 default: 42 return nil, nil, ErrBadKeyType 43 } 44 } 45 46 // PrivKeyToStdKey converts libp2p/go-libp2p-core/crypto private keys to standard library (and secp256k1) private keys 47 func PrivKeyToStdKey(priv PrivKey) (crypto.PrivateKey, error) { 48 if priv == nil { 49 return nil, ErrNilPrivateKey 50 } 51 switch p := priv.(type) { 52 case *opensslPrivateKey: 53 raw, err := p.Raw() 54 if err != nil { 55 return nil, err 56 } 57 return x509.ParsePKCS1PrivateKey(raw) 58 case *ECDSAPrivateKey: 59 return p.priv, nil 60 case *Ed25519PrivateKey: 61 return &p.k, nil 62 case *Secp256k1PrivateKey: 63 return p, nil 64 case *SM2PrivateKey: 65 return p.priv, nil 66 default: 67 return nil, ErrBadKeyType 68 } 69 } 70 71 // PubKeyToStdKey converts libp2p/go-libp2p-core/crypto private keys to standard library (and secp256k1) public keys 72 func PubKeyToStdKey(pub PubKey) (crypto.PublicKey, error) { 73 if pub == nil { 74 return nil, ErrNilPublicKey 75 } 76 switch p := pub.(type) { 77 case *opensslPublicKey: 78 raw, err := p.Raw() 79 if err != nil { 80 return nil, err 81 } 82 return x509.ParsePKIXPublicKey(raw) 83 case *ECDSAPublicKey: 84 return p.pub, nil 85 case *Ed25519PublicKey: 86 return p.k, nil 87 case *Secp256k1PublicKey: 88 return p, nil 89 case *SM2PublicKey: 90 return p.pub, nil 91 default: 92 return nil, ErrBadKeyType 93 } 94 }