在go语言中DSA(数字签名算法)包函数的示例代码
关于如何充分利用crypto/dsa软件包的例子或教程并不多。
在本文中学习如何利用crypto/dsa函数对我们的信息进行数字签名并验证签名。
下面的源代码将:
生成一个私钥
从生成的私钥中提取公钥
使用私钥进行签名
使用公钥来验证签名
示例代码:
dsaexample.go
package main
import (
"crypto/rand"
"crypto/dsa"
"crypto/md5"
"hash"
"fmt"
"os"
"io"
"math/big"
)
func main() {
params := new(dsa.Parameters)
// see http://golang.org/pkg/crypto/dsa/#ParameterSizes
if err := dsa.GenerateParameters(params, rand.Reader, dsa.L1024N160); err != nil {
fmt.Println(err)
os.Exit(1)
}
privatekey := new(dsa.PrivateKey)
privatekey.PublicKey.Parameters = *params
dsa.GenerateKey(privatekey, rand.Reader) // this generates a public & private key pair
var pubkey dsa.PublicKey
pubkey = privatekey.PublicKey
fmt.Println("Private Key :")
fmt.Printf("%x \n", privatekey)
fmt.Println("Public Key :")
fmt.Printf("%x \n",pubkey)
// Sign
var h hash.Hash
h = md5.New()
r := big.NewInt(0)
s := big.NewInt(0)
io.WriteString(h, "This is the message to be signed and verified!")
signhash := h.Sum(nil)
r, s, err := dsa.Sign(rand.Reader, privatekey, signhash)
if err != nil {
fmt.Println(err)
}
signature := r.Bytes()
signature = append(signature, s.Bytes()...)
fmt.Printf("Signature : %x\n", signature)
// Verify
verifystatus := dsa.Verify(&pubkey, signhash, r, s)
fmt.Println(verifystatus) // should be true
// we add additional data to change the signhash
io.WriteString(h, "This message is NOT to be signed and verified!")
signhash = h.Sum(nil)
verifystatus = dsa.Verify(&pubkey, signhash, r, s)
fmt.Println(verifystatus) // should be false
}
输出:
(注意:每次执行代码时,公钥、私钥和签名值都会不同)
Private Key :
{{{de735666a2220833b0b07f88c5ff30434e4af53f5e53c0e397057902a.....}
Public Key : {{de735666a2220833b0b07f88c5ff30434e4af53f5e53c0e397057902a......}
Signature :
75483cc98f4587b9ab4e8336b873e8eddd2fb41b594db267ce4bc09285ec15d63d17f6ec82989cd3
true
false
相关文章