signature.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. // Copyright (C) 2015 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. // Package signature provides simple methods to create and verify signatures
  7. // in PEM format.
  8. package signature
  9. import (
  10. "crypto/ecdsa"
  11. "crypto/elliptic"
  12. "crypto/rand"
  13. "crypto/sha256"
  14. "crypto/x509"
  15. "encoding/asn1"
  16. "encoding/pem"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "math/big"
  21. )
  22. // GenerateKeys returns a new key pair, with the private and public key
  23. // encoded in PEM format.
  24. func GenerateKeys() (privKey []byte, pubKey []byte, err error) {
  25. // Generate a new key pair
  26. key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
  27. if err != nil {
  28. return nil, nil, err
  29. }
  30. // Marshal the private key
  31. bs, err := x509.MarshalECPrivateKey(key)
  32. if err != nil {
  33. return nil, nil, err
  34. }
  35. // Encode it in PEM format
  36. privKey = pem.EncodeToMemory(&pem.Block{
  37. Type: "EC PRIVATE KEY",
  38. Bytes: bs,
  39. })
  40. // Marshal the public key
  41. bs, err = x509.MarshalPKIXPublicKey(key.Public())
  42. if err != nil {
  43. return nil, nil, err
  44. }
  45. // Encode it in PEM format
  46. pubKey = pem.EncodeToMemory(&pem.Block{
  47. Type: "EC PUBLIC KEY",
  48. Bytes: bs,
  49. })
  50. return
  51. }
  52. // Sign computes the hash of data and signs it with the private key, returning
  53. // a signature in PEM format.
  54. func Sign(privKeyPEM []byte, data io.Reader) ([]byte, error) {
  55. // Parse the private key
  56. key, err := loadPrivateKey(privKeyPEM)
  57. if err != nil {
  58. return nil, err
  59. }
  60. // Hash the reader data
  61. hash, err := hashReader(data)
  62. if err != nil {
  63. return nil, err
  64. }
  65. // Sign the hash
  66. r, s, err := ecdsa.Sign(rand.Reader, key, hash)
  67. if err != nil {
  68. return nil, err
  69. }
  70. // Marshal the signature using ASN.1
  71. sig, err := marshalSignature(r, s)
  72. if err != nil {
  73. return nil, err
  74. }
  75. // Encode it in a PEM block
  76. bs := pem.EncodeToMemory(&pem.Block{
  77. Type: "SIGNATURE",
  78. Bytes: sig,
  79. })
  80. return bs, nil
  81. }
  82. // Verify computes the hash of data and compares it to the signature using the
  83. // given public key. Returns nil if the signature is correct.
  84. func Verify(pubKeyPEM []byte, signature []byte, data io.Reader) error {
  85. // Parse the public key
  86. key, err := loadPublicKey(pubKeyPEM)
  87. if err != nil {
  88. return err
  89. }
  90. // Parse the signature
  91. block, _ := pem.Decode(signature)
  92. r, s, err := unmarshalSignature(block.Bytes)
  93. if err != nil {
  94. return err
  95. }
  96. // Compute the hash of the data
  97. hash, err := hashReader(data)
  98. if err != nil {
  99. return err
  100. }
  101. // Verify the signature
  102. if !ecdsa.Verify(key, hash, r, s) {
  103. return errors.New("incorrect signature")
  104. }
  105. return nil
  106. }
  107. // hashReader returns the SHA256 hash of the reader
  108. func hashReader(r io.Reader) ([]byte, error) {
  109. h := sha256.New()
  110. if _, err := io.Copy(h, r); err != nil {
  111. return nil, err
  112. }
  113. hash := []byte(fmt.Sprintf("%x", h.Sum(nil)))
  114. return hash, nil
  115. }
  116. // loadPrivateKey returns the ECDSA private key structure for the given PEM
  117. // data.
  118. func loadPrivateKey(bs []byte) (*ecdsa.PrivateKey, error) {
  119. block, _ := pem.Decode(bs)
  120. return x509.ParseECPrivateKey(block.Bytes)
  121. }
  122. // loadPublicKey returns the ECDSA public key structure for the given PEM
  123. // data.
  124. func loadPublicKey(bs []byte) (*ecdsa.PublicKey, error) {
  125. // Decode and parse the public key PEM block
  126. block, _ := pem.Decode(bs)
  127. intf, err := x509.ParsePKIXPublicKey(block.Bytes)
  128. if err != nil {
  129. return nil, err
  130. }
  131. // It should be an ECDSA public key
  132. pk, ok := intf.(*ecdsa.PublicKey)
  133. if !ok {
  134. return nil, errors.New("unsupported public key format")
  135. }
  136. return pk, nil
  137. }
  138. // A wrapper around the signature integers so that we can marshal and
  139. // unmarshal them.
  140. type signature struct {
  141. R, S *big.Int
  142. }
  143. // marhalSignature returns ASN.1 encoded bytes for the given integers,
  144. // suitable for PEM encoding.
  145. func marshalSignature(r, s *big.Int) ([]byte, error) {
  146. sig := signature{
  147. R: r,
  148. S: s,
  149. }
  150. bs, err := asn1.Marshal(sig)
  151. if err != nil {
  152. return nil, err
  153. }
  154. return bs, nil
  155. }
  156. // unmarshalSignature returns the R and S integers from the given ASN.1
  157. // encoded signature.
  158. func unmarshalSignature(sig []byte) (r *big.Int, s *big.Int, err error) {
  159. var ts signature
  160. _, err = asn1.Unmarshal(sig, &ts)
  161. if err != nil {
  162. return nil, nil, err
  163. }
  164. return ts.R, ts.S, nil
  165. }