Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

导出sm2.PublicKey #33

Closed
tossp opened this issue Mar 3, 2022 · 4 comments
Closed

导出sm2.PublicKey #33

tossp opened this issue Mar 3, 2022 · 4 comments

Comments

@tossp
Copy link

tossp commented Mar 3, 2022

请问可以添加导出sm2.PublicKey吗?

在实现协商密钥的时候需要单独用到sm2.PublicKey,需要和crypto包保持兼容。

// GenerateSharedSecret 生成共享密钥
func GenerateSharedSecret(priv crypto.PrivateKey, pub crypto.PublicKey) ([]byte, error) {
	var (
		x1    *big.Int
		y1    *big.Int
		k     []byte
		curve elliptic.Curve
	)
	switch key := priv.(type) {
	case *ecdsa.PrivateKey:
		k = key.D.Bytes()
		pubKey, ok := pub.(*ecdsa.PublicKey)
		if !ok { 
			return nil, errors.New("pub only support ecdsa.PublicKey point type")
		}
		x1 = pubKey.X
		y1 = pubKey.Y
		curve = pubKey.Curve
	case *sm2.PrivateKey:
		k = key.D.Bytes()
		pubKey, ok := pub.(*sm2.PublicKey)
		if !ok { 
			return nil, errors.New("pub only support sm2.PublicKey point type")
		}
		x1 = pubKey.X
		y1 = pubKey.Y
		curve = pubKey.Curve
	default: 
		return nil, errors.New("priv only support ecdsa.PrivateKey and sm2.PrivateKey")
	}
        x, _ := curve.ScalarMult(x1, y1, k)
	return x.Bytes(), nil
}
@emmansun
Copy link
Owner

emmansun commented Mar 3, 2022

不是很理解你的问题,这个包没有定义自己的公钥数据结构啊。感觉你的两个case可以合并成一个:

case *ecdsa.PrivateKey,*sm2.PrivateKey:

@tossp
Copy link
Author

tossp commented Mar 4, 2022

是的,先前依赖的tjfoc/gmsm

没有定义自己的公钥数据结构,代码可读性会显得有点怪
比如这个,明明是sm2,单看函数签名却是ecdsa

// FromsPub 公钥 -> []byte
func FromsPub(pub *ecdsa.PublicKey) []byte {
	if pub == nil || pub.X == nil || pub.Y == nil {
		return nil
	}
	return elliptic.Marshal(pub.Curve, pub.X, pub.Y)
}

// ToPub []byte -> 公钥
func ToPub(pub []byte) *ecdsa.PublicKey {
	if len(pub) == 0 {
		return nil
	}
	curve := sm2.P256()
	x, y := elliptic.Unmarshal(curve, pub)
	return &ecdsa.PublicKey{Curve: curve, X: x, Y: y}
}

@emmansun
Copy link
Owner

emmansun commented Mar 4, 2022

SM2曲线和NIST P-256只是参数不同而已,所以数据结构是一样的,就象NIST P-224 P-256 P-384 P-512,SM2曲线无需扩展此结构也没有SM2曲线特殊的方法需要实现。还有就是考虑SM2-256曲线理论上是和SM2加解密、签名验签算法分开的,其实无需深度绑定。你的ToPub方法,如果加上curve参数,其实是适用所有NIST P系列和SM2 256曲线的。

@tossp
Copy link
Author

tossp commented Mar 5, 2022

了解,感谢您的答复

@tossp tossp closed this as completed Mar 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants