pgp.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // signFile reads the contents of an input file and signs it (in armored format)
  17. // with the key provided, placing the signature into the output file.
  18. package build
  19. import (
  20. "bytes"
  21. "fmt"
  22. "os"
  23. "golang.org/x/crypto/openpgp"
  24. )
  25. // PGPSignFile parses a PGP private key from the specified string and creates a
  26. // signature file into the output parameter of the input file.
  27. //
  28. // Note, this method assumes a single key will be container in the pgpkey arg,
  29. // furthermore that it is in armored format.
  30. func PGPSignFile(input string, output string, pgpkey string) error {
  31. // Parse the keyring and make sure we only have a single private key in it
  32. keys, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(pgpkey))
  33. if err != nil {
  34. return err
  35. }
  36. if len(keys) != 1 {
  37. return fmt.Errorf("key count mismatch: have %d, want %d", len(keys), 1)
  38. }
  39. // Create the input and output streams for signing
  40. in, err := os.Open(input)
  41. if err != nil {
  42. return err
  43. }
  44. defer in.Close()
  45. out, err := os.Create(output)
  46. if err != nil {
  47. return err
  48. }
  49. defer out.Close()
  50. // Generate the signature and return
  51. return openpgp.ArmoredDetachSign(out, keys[0], in, nil)
  52. }
  53. // PGPKeyID parses an armored key and returns the key ID.
  54. func PGPKeyID(pgpkey string) (string, error) {
  55. keys, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(pgpkey))
  56. if err != nil {
  57. return "", err
  58. }
  59. if len(keys) != 1 {
  60. return "", fmt.Errorf("key count mismatch: have %d, want %d", len(keys), 1)
  61. }
  62. return keys[0].PrimaryKey.KeyIdString(), nil
  63. }