github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/internal/build/pgp.go (about) 1 // This file is part of the go-sberex library. The go-sberex library is 2 // free software: you can redistribute it and/or modify it under the terms 3 // of the GNU Lesser General Public License as published by the Free 4 // Software Foundation, either version 3 of the License, or (at your option) 5 // any later version. 6 // 7 // The go-sberex library is distributed in the hope that it will be useful, 8 // but WITHOUT ANY WARRANTY; without even the implied warranty of 9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 10 // General Public License <http://www.gnu.org/licenses/> for more details. 11 12 // signFile reads the contents of an input file and signs it (in armored format) 13 // with the key provided, placing the signature into the output file. 14 15 package build 16 17 import ( 18 "bytes" 19 "fmt" 20 "os" 21 22 "golang.org/x/crypto/openpgp" 23 ) 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 46 out, err := os.Create(output) 47 if err != nil { 48 return err 49 } 50 defer out.Close() 51 52 // Generate the signature and return 53 return openpgp.ArmoredDetachSign(out, keys[0], in, nil) 54 }