golang实现摘要签名和验证

栏目: IT技术 · 发布时间: 4年前

内容简介:golang实现摘要签名和验证的过程:两个步骤:下面是代码原文:

golang实现摘要签名和验证的过程:

两个步骤:

  1. 利用私钥对一个摘要进行签名。
$ ./test -command sign -key ./privatekey.pem -text "12345"
MEUCIE7DsGmTHJ3VGZec2UF9hRX7jq9Yd7F2kS7kEL132js8AiEA/ZlyIpo86Rn3waR8m2c4BtQPu8cNjYAnroibK+ujslY=
  1. 利用公钥验证签名是否有效。
$ ./test -command verify -cert ./publickey.pem -text "12345" -sign "MEQCIFuvcVHlztAN7YVehgCDYzVSo1Q10iTKeJE5ydxzfih5AiAC2ETt/8XuE1VHaGkLsiJkRSueh65Leq2VKkmFKxB/sQ=="
Successed to verify Signature and nonce

下面是代码原文:

package main

import (
    "fmt"
    "flag"
    "io/ioutil"
    "math/big"
    "crypto/ecdsa"
    "crypto/rand"
    "crypto/sha256"
    "crypto/x509"
    "encoding/asn1"
    "encoding/base64"
    "encoding/pem"
)

type ECDSASignature struct {
    R, S *big.Int
}

var (
    command     string
    certfile    string
    keyfile     string
    text        string
    sign        string
)

func main() {
    flag.StringVar(&command,    "command",  "",   "Command: sign/verify")
    flag.StringVar(&keyfile,    "key",      "",   "Private key file")
    flag.StringVar(&certfile,   "cert",     "",   "Public key file")
    flag.StringVar(&text,       "text",     "",   "Text content to be signed")
    flag.StringVar(&sign,       "sign",     "",   "Signed content to be verifed")
    flag.Parse()

    switch command {
    case "sign":
        if keyfile == "" || text == "" {
            fmt.Printf("ERROR: either key file or text is empty\n")
            return
        }
        Sign(keyfile, text)
    case "verify":
        if certfile == "" || text == "" || sign == "" {
            fmt.Printf("ERROR: either key file or text or sign is empty\n")
            return
        }
        Verify(certfile, text, sign)
    default:
        fmt.Printf("ERROR: unknown command\n")
        return
    }

}

func Sign(keyFile, text string) {
    keyBuff, err := ioutil.ReadFile(keyFile)
    if err != nil {
        fmt.Printf("ERROR: failed to read keystore file: %s, error: %v\n", keyFile, err)
        return
    }

    block, _ := pem.Decode(keyBuff)
    if block == nil {
        fmt.Printf("ERROR: block of decoded private key is nil\n")
        return
    }

    privKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
    if err != nil {
        fmt.Printf("ERROR: failed get ECDSA private key, %v\n", err)
        return
    }
    ecPrivKey := privKey.(*ecdsa.PrivateKey)


    hash := sha256.Sum256([]byte(text))
    r, s, err := ecdsa.Sign(rand.Reader, ecPrivKey, hash[:])
    if err != nil {
        fmt.Printf("ERROR: failed to get signature, %v\n", err)
        return
    }

    // asn1 output DER format
    signature, err := asn1.Marshal(ECDSASignature{
        R: r,
        S: s,
    })
    if err != nil {
        fmt.Printf("ERROR: asn1.Marshal ECDSA signature: %v\n", err)
        return
    }

    fmt.Printf("%s\n", base64.StdEncoding.EncodeToString(signature))
}

func Verify(certFile, text string, sign string) {
    certBuff, err := ioutil.ReadFile(certFile)
    if err != nil {
        fmt.Printf("ERROR: failed to read keystore file: %s, error: %s\n", certFile, err)
        return
    }

    block, _ := pem.Decode(certBuff)
    if block == nil {
        fmt.Printf("ERROR: block of decoded private key is nil\n")
        return
    }

    cert, err := x509.ParseCertificate(block.Bytes)
    if err != nil {
        fmt.Printf("ERROR: failed get ECDSA private key, error: %v\n", err)
        return
    }

    arr := []byte(text)
    h := sha256.New()
    h.Write(arr)
    hashed := h.Sum(nil)

    signatureDec, _ := base64.StdEncoding.DecodeString(sign)
    sig := new(ECDSASignature)
    _, err = asn1.Unmarshal(signatureDec, sig)
    if err != nil {
        fmt.Printf("ERROR: failed unmashalling signature, error: %v", err)
        return
    }

    pub, _ := cert.PublicKey.(*ecdsa.PublicKey)
    if !ecdsa.Verify(pub, hashed[:], sig.R, sig.S) {
        fmt.Printf("ERROR: Failed to verify Signature: %v\n", err)
        return
    }
    fmt.Printf("Successed to verify Signature and nonce\n")
    return
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

图论算法理论、实现及应用

图论算法理论、实现及应用

王桂平//王衍//任嘉辰 / 北京大学 / 2011-1 / 54.00元

《图论算法理论、实现及应用》系统地介绍了图论算法理论,并选取经典的ACM/ICPC竞赛题目为例题阐述图论算法思想,侧重于图论算法的程序实现及应用。《图论算法理论、实现及应用》第1章介绍图的基本概念和图的两种存储表示方法:邻接矩阵和邻接表,第2~9章分别讨论图的遍历与活动网络问题,树与图的生成树,最短路径问题,可行遍性问题,网络流问题,支配集、覆盖集、独立集与匹配,图的连通性问题,平面图及图的着色问......一起来看看 《图论算法理论、实现及应用》 这本书的介绍吧!

html转js在线工具
html转js在线工具

html转js在线工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具