【发布时间】:2014-02-09 11:26:25
【问题描述】:
我需要签署一条消息以提交到远程服务(通过 websocket)。为此,我需要基于整数(我的用户 ID)和密码(base64 编码的字符串)构造一个私钥,并使用 SHA224 进行哈希处理。我正在使用 golang 和 crypto/ecdsa 以及用于字节编码等的随附包。
这是我的文档:
签名使用椭圆曲线数字签名算法 (ECDSA) 编码消息包含:用户 ID、服务器 Nonce、客户端节点和 私钥。生成私钥散列您的用户 ID 和您的 SHA224 密码。
这是我的功能:
func NewKey(userId int64, pass string) (prKey ecdsa.PrivateKey) {
buf := new(bytes.Buffer)
binary.Write(buf, binary.BigEndian, userId)
passArr := []byte(pass)
sha := sha256.New224()
sha.Write(buf.Bytes())
sha.Write(passArr)
sum := sha.Sum(nil)
var in int64
reader := bytes.NewReader(sum)
err := binary.Read(reader, binary.BigEndian, &in)
if err != nil {
log.Fatal(err)
}
prKey.D = big.NewInt(in)
prKey.PublicKey.Curve = elliptic.P224()
return prKey
}
我对这个函数的意图是:
散列 userId 并使用 SHA224 正确传递
[]byte。将其读入
int64,然后将其用作私钥正确构造
ecdsa.PrivateKey的实例和对应的ecdsa.PublicKey返回用于
ecdsa.Sign()函数调用的密钥
然后我签署另一条由 userId(整数)和两个 nonce 组成的消息。
以下是我在消息上签名的方式:
key := NewKey(userId, pass) // the above func
msg := sha256.New224().Sum([]byte(userId + srNonce + clNonce))
r, s, err := ecdsa.Sign(rand.Reader, &key, msg)
sig := []string{enc(r.String()), enc(s.String())}
问题:
我的
NewKeyfunc 正确吗?r和s组件非常大 - 大概是因为我正在使用int64。这可能是个问题吗?sha256.New224().Sum([]byte(userId + pass))行是否“正确”包含这两项?如何正确创建我的私钥(假设它是错误的)并随后签署消息?
我对 ECDSA 非常陌生,并且一般具有基本的加密知识。
【问题讨论】:
-
(1) 你可能不想要
binary.PutUvarint,而是 binary.LittleEndian.PutUint64`(或BigEndian,如果合适的话)。 (2) 你能提供一个描述你试图实现的协议的链接吗?没有它,很难说哪里出了问题。 -
我将替换那个 PutUvarint 调用 - 谢谢。更新了我的小文档。
-
其实我现在用的是
PutVarint,因为它是一个有符号的64位整数。 -
encoding/binary的 Varint 编码是一种来自 Protocol Buffers 规范的可变长度编码。如果您只想将整数编码为 8 个字节,那么您不需要PutVarint。 -
使用我在第一条评论中提到的内容:
binary.LittleEndian.PutUint64或binary.BigEndian.PutUint64。如果您有一个有符号整数,则需要先将其转换为无符号变体。
标签: cryptography go ecdsa