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