在包golang.org/x/crypto/nacl/sign
中,Sign函数有一个out []byte
参数,它返回一个字节切片。
阅读源代码,我正在努力弄清楚如何正确使用它们,它们是头部和尾部,尽管在下面的示例中,生成的字节切片为零 len。
请看下面的例子,
package main
import (
"crypto/rand"
"encoding/base64"
"fmt"
"golang.org/x/crypto/nacl/sign"
)
func main() {
_, priv, err := sign.GenerateKey(rand.Reader)
if err != nil {
panic(err)
}
msg := []byte("hello world!")
out := make([]byte, 0, len(msg)+sign.Overhead)
ret := sign.Sign(out, msg, priv)
fmt.Printf("len(msg): %v %s\n", len(msg), msg)
fmt.Printf("len(out): %v %v\n", len(out), base64.StdEncoding.EncodeToString(out))
fmt.Printf("len(ret): %v %v\n", len(ret), base64.StdEncoding.EncodeToString(ret))
}
// Output:
// len(msg): 12 hello world!
// len(out): 0
// len(ret): 76 h+ZkFoWxuxOj7zV3tekiQz/z/yfuvXNUHxBjklo4iGBy7PfCEwvAiy3gi7GnuYGWB3SMxuxHtV5tNuUL1b3kAGhlbGxvIHdvcmxkIQ==
我不明白为什么 Sign 会同时返回和返回。我不确定要签署.Sign 的输出缓冲区应该多长时间。
相反,这个例子有效,但它是否正确?
package main
import (
"crypto/rand"
"encoding/base64"
"fmt"
"golang.org/x/crypto/nacl/sign"
)
func main() {
pub, priv, err := sign.GenerateKey(rand.Reader)
if err != nil {
panic(err)
}
msg := []byte("hello world!")
out := make([]byte, 0, len(msg)+sign.Overhead)
ret := sign.Sign(out, msg, priv)
fmt.Printf("len(msg): %v %s\n", len(msg), msg)
fmt.Printf("len(out): %v %v\n", len(out), base64.StdEncoding.EncodeToString(out))
fmt.Printf("len(ret): %v %v\n", len(ret), base64.StdEncoding.EncodeToString(ret))
openOut := make([]byte, 0, len(ret)-sign.Overhead)
res, ok := sign.Open(openOut, ret, pub)
if !ok {
panic("failed to open signed message")
}
fmt.Printf("len(res): %v %s\n", len(res), res)
}
// Output:
// len(msg): 12 hello world!
// len(out): 0
// len(ret): 76 h+ZkFoWxuxOj7zV3tekiQz/z/yfuvXNUHxBjklo4iGBy7PfCEwvAiy3gi7GnuYGWB3SMxuxHtV5tNuUL1b3kAGhlbGxvIHdvcmxkIQ==
// len(res): 12 hello world!
期待一些解释和正确性帮助。