github.com/olivere/camlistore@v0.0.0-20140121221811-1b7ac2da0199/pkg/jsonsign/sign_normal.go (about) 1 // +build !appengine 2 3 /* 4 Copyright 2013 Google Inc. 5 6 Licensed under the Apache License, Version 2.0 (the "License"); 7 you may not use this file except in compliance with the License. 8 You may obtain a copy of the License at 9 10 http://www.apache.org/licenses/LICENSE-2.0 11 12 Unless required by applicable law or agreed to in writing, software 13 distributed under the License is distributed on an "AS IS" BASIS, 14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 See the License for the specific language governing permissions and 16 limitations under the License. 17 */ 18 19 package jsonsign 20 21 import ( 22 "errors" 23 "fmt" 24 "log" 25 "os" 26 27 "camlistore.org/pkg/misc/gpgagent" 28 "camlistore.org/pkg/misc/pinentry" 29 "camlistore.org/third_party/code.google.com/p/go.crypto/openpgp" 30 ) 31 32 func (fe *FileEntityFetcher) decryptEntity(e *openpgp.Entity) error { 33 // TODO: syscall.Mlock a region and keep pass phrase in it. 34 pubk := &e.PrivateKey.PublicKey 35 desc := fmt.Sprintf("Need to unlock GPG key %s to use it for signing.", 36 pubk.KeyIdShortString()) 37 38 conn, err := gpgagent.NewConn() 39 switch err { 40 case gpgagent.ErrNoAgent: 41 fmt.Fprintf(os.Stderr, "Note: gpg-agent not found; resorting to on-demand password entry.\n") 42 case nil: 43 defer conn.Close() 44 req := &gpgagent.PassphraseRequest{ 45 CacheKey: "camli:jsonsign:" + pubk.KeyIdShortString(), 46 Prompt: "Passphrase", 47 Desc: desc, 48 } 49 for tries := 0; tries < 2; tries++ { 50 pass, err := conn.GetPassphrase(req) 51 if err == nil { 52 err = e.PrivateKey.Decrypt([]byte(pass)) 53 if err == nil { 54 return nil 55 } 56 req.Error = "Passphrase failed to decrypt: " + err.Error() 57 conn.RemoveFromCache(req.CacheKey) 58 continue 59 } 60 if err == gpgagent.ErrCancel { 61 return errors.New("jsonsign: failed to decrypt key; action canceled") 62 } 63 log.Printf("jsonsign: gpgagent: %v", err) 64 } 65 default: 66 log.Printf("jsonsign: gpgagent: %v", err) 67 } 68 69 pinReq := &pinentry.Request{Desc: desc, Prompt: "Passphrase"} 70 for tries := 0; tries < 2; tries++ { 71 pass, err := pinReq.GetPIN() 72 if err == nil { 73 err = e.PrivateKey.Decrypt([]byte(pass)) 74 if err == nil { 75 return nil 76 } 77 pinReq.Error = "Passphrase failed to decrypt: " + err.Error() 78 continue 79 } 80 if err == pinentry.ErrCancel { 81 return errors.New("jsonsign: failed to decrypt key; action canceled") 82 } 83 log.Printf("jsonsign: pinentry: %v", err) 84 } 85 return fmt.Errorf("jsonsign: failed to decrypt key %q", pubk.KeyIdShortString()) 86 }