fabric bccsp的sign 到底是什么含义? 做了什么操作?按照下面的代码进行验证
func TestEcdsaSignerSign(t *testing.T) {
t.Parallel()
signer := &ecdsaSigner{}
verifierPrivateKey := &ecdsaPrivateKeyVerifier{}
verifierPublicKey := &ecdsaPublicKeyKeyVerifier{}
// Generate a key
lowLevelKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
k := &ecdsaPrivateKey{lowLevelKey}
pk, err := k.PublicKey()
require.NoError(t, err)
// Sign
msg := []byte("Hello World")
sigma, err := signer.Sign(k, msg, nil)
require.NoError(t, err)
require.NotNil(t, sigma)
// Verify
valid, err := verifyECDSA(&lowLevelKey.PublicKey, sigma, msg, nil)
require.NoError(t, err)
require.True(t, valid)
valid, err = verifierPrivateKey.Verify(k, sigma, msg, nil)
require.NoError(t, err)
require.True(t, valid)
valid, err = verifierPublicKey.Verify(pk, sigma, msg, nil)
require.NoError(t, err)
require.True(t, valid)
}
(1) 构造实例,ecdsaSigner,ecdsaPrivateVerifier, ecdsaPublicKetKeyVerifier
type ecdsaSigner struct{}
func (s *ecdsaSigner) Sign(k bccsp.Key, digest []byte, opts bccsp.SignerOpts) ([]byte, error) {
return signECDSA(k.(*ecdsaPrivateKey).privKey, digest, opts)
}
type ecdsaPrivateKeyVerifier struct{}
func (v *ecdsaPrivateKeyVerifier) Verify(k bccsp.Key, signature, digest []byte, opts bccsp.SignerOpts) (bool, error) {
return verifyECDSA(&(k.(*ecdsaPrivateKey).privKey.PublicKey), signature, digest, opts)
}
type ecdsaPublicKeyKeyVerifier struct{}
func (v *ecdsaPublicKeyKeyVerifier) Verify(k bccsp.Key, signature, digest []byte, opts bccsp.SignerOpts) (bool, error) {
return verifyECDSA(k.(*ecdsaPublicKey).pubKey, signature, digest, opts)
}
(2) 生成一个Key
lowLevelKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
(3) 用这个key构造ecdsaPrivateKey
k := &ecdsaPrivateKey{lowLevelKey}
(4) 用私钥对信息进行签名
参数是私钥和信息
msg := []byte("Hello World")
sigma, err := signer.Sign(k, msg, nil)
(5) 验证公钥,签名和信息
valid, err := verifyECDSA(&lowLevelKey.PublicKey, sigma, msg, nil)
func verifyECDSA(k *ecdsa.PublicKey, signature, digest []byte, opts bccsp.SignerOpts) (bool, error) {
r, s, err := utils.UnmarshalECDSASignature(signature)
if err != nil {
return false, fmt.Errorf("Failed unmashalling signature [%s]", err)
}
lowS, err := utils.IsLowS(k, s)
if err != nil {
return false, err
}
if !lowS {
return false, fmt.Errorf("Invalid S. Must be smaller than half the order [%s][%s].", s, utils.GetCurveHalfOrdersAt(k.Curve))
}
return ecdsa.Verify(k, digest, r, s), nil
}
(5-1) 验证过程
r, s, err := utils.UnmarshalECDSASignature(signature)
就是从签名中解码出信息
(5-2) 检查k 是否是low-s,lowS返回true
lowS, err := utils.IsLowS(k, s)
(5-3) 调用ecdsa的verify方法
Verify使用公钥pub验证哈希的r, s中的签名。它的返回值记录签名是否有效。具体的方法有点复杂,再不细看。
return ecdsa.Verify(k, digest, r, s), nil
(6)验证私钥和签名、信息之间
valid, err = verifierPrivateKey.Verify(k, sigma, msg, nil)
同样调用的是verifyECDSA,但是参数不同
return verifyECDSA(&(k.(*ecdsaPrivateKey).privKey.PublicKey), signature, digest, opts)
(7) 验证公钥和签名、信息之间的关系
valid, err = verifierPublicKey.Verify(pk, sigma, msg, nil)