1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
| package main import ( "crypto/ecdsa" "crypto/elliptic" "crypto/sha256" "crypto/x509" "encoding/pem" "errors" "fmt" "io/ioutil" "log" "os" "strings" )
var randSign = "22220316zafes20180lk7zafes20180619zafepikas"
var randKey = "lk0f7279c18d439459435s714797c9680335a320"
var PriKey *ecdsa.PrivateKey var PubKey *ecdsa.PublicKey
func init() { priFile, _ := os.Create("ec-pri.pem") pubFile, _ := os.Create("ec-pub.pem") if err := generateKey(priFile, pubFile); err != nil { log.Println(err) os.Exit(1) } if err := loadKey(); err != nil { log.Println(err) os.Exit(1) } } func main() {
text := "hello dalgurak" hashText := sha256.Sum256([]byte(text)) r, s, err := ecdsa.Sign(strings.NewReader(randSign), PriKey, hashText) if err != nil { log.Println(err) os.Exit(1) }
b := ecdsa.Verify(PubKey, hashText, r, s) fmt.Println(b) }
func generateKey(priFile, pubFile *os.File) error { lenth := len(randKey) if lenth < 224/8 { return errors.New("私钥长度太短,至少为36位!") } var curve elliptic.Curve if lenth > 521/8+8 { curve = elliptic.P521() } else if lenth > 384/8+8 { curve = elliptic.P384() } else if lenth > 256/8+8 { curve = elliptic.P256() } else if lenth > 224/8+8 { curve = elliptic.P224() } priKey, err := ecdsa.GenerateKey(curve, strings.NewReader(randKey)) if err != nil { return err } priBytes, err := x509.MarshalECPrivateKey(priKey) if err != nil { return err } priBlock := pem.Block{ Type: "ECD PRIVATE KEY", Bytes: priBytes, } if err := pem.Encode(priFile, &priBlock); err != nil { return err } pubBytes, err := x509.MarshalPKIXPublicKey(&priKey.PublicKey) if err != nil { return err } pubBlock := pem.Block{ Type: "ECD PUBLIC KEY", Bytes: pubBytes, } if err := pem.Encode(pubFile, &pubBlock); err != nil { return err } return nil }
func loadKey() error { pri, _ := ioutil.ReadFile("ec-pri.pem") pub, _ := ioutil.ReadFile("ec-pub.pem") block, _ := pem.Decode(pri) var err error PriKey, err = x509.ParseECPrivateKey(block.Bytes) if err != nil { return err } block, _ = pem.Decode(pub) var i interface{} i, err = x509.ParsePKIXPublicKey(block.Bytes) if err != nil { return err } var ok bool PubKey, ok = i.(*ecdsa.PublicKey) if !ok { return errors.New("the public conversion error") } return nil }
|