本文整理匯總了Golang中code/google/com/p/go/crypto/openpgp.ReadKeyRing函數的典型用法代碼示例。如果您正苦於以下問題:Golang ReadKeyRing函數的具體用法?Golang ReadKeyRing怎麽用?Golang ReadKeyRing使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了ReadKeyRing函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: main
func main() {
pubRingFile, _ := os.Open("/home/brad/.gnupg/pubring.gpg")
pubRing, _ := openpgp.ReadKeyRing(pubRingFile)
privRingFile, _ := os.Open("/home/brad/.gnupg/secring.gpg")
privRing, _ := openpgp.ReadKeyRing(privRingFile)
myPrivateKey := getKeyByEmail(privRing, "[email protected]")
theirPublicKey := getKeyByEmail(pubRing, "[email protected]")
w, _ := armor.Encode(os.Stdout, "PGP MESSAGE", nil)
plaintext, _ := openpgp.Encrypt(w, []*openpgp.Entity{theirPublicKey}, myPrivateKey, nil)
fmt.Fprintf(plaintext, "Hello from golang.\n")
plaintext.Close()
w.Close()
fmt.Printf("\n")
}
示例2: processSecretKeyRing
func processSecretKeyRing() (entity *openpgp.Entity, entitylist openpgp.EntityList) {
// Get default secret keyring location
usr, err := user.Current()
if err != nil {
log.Fatal(err)
}
jaegerSecretKeyRing := fmt.Sprintf("%v/.gnupg/jaeger_secring.gpg", usr.HomeDir)
secretKeyRing := ""
if _, err := os.Stat(jaegerSecretKeyRing); err == nil {
secretKeyRing = jaegerSecretKeyRing
} else {
secretKeyRing = fmt.Sprintf("%v/.gnupg/secring.gpg", usr.HomeDir)
}
debug.Printf("secretKeyRing file:", secretKeyRing)
secretKeyRingBuffer, err := os.Open(secretKeyRing)
if err != nil {
panic(err)
}
entitylist, err = openpgp.ReadKeyRing(secretKeyRingBuffer)
if err != nil {
log.Fatal(err)
}
entity = entitylist[0]
debug.Printf("Private key default keyring:", entity.Identities)
return entity, entitylist
}
示例3: encrypt
func encrypt(ringPath string, input io.Reader, output io.Writer) error {
ringFile, err := os.Open(ringPath)
if err != nil {
return err
}
defer ringFile.Close()
ring, err := openpgp.ReadKeyRing(ringFile)
if err != nil {
return err
}
// TODO: Select proper key
key := ring[0]
plaintext, err := openpgp.Encrypt(output, []*openpgp.Entity{key}, nil, nil, nil)
if err != nil {
return err
}
defer plaintext.Close()
if _, err := io.Copy(plaintext, input); err != nil {
return err
}
return nil
}
示例4: GetSigner
func GetSigner(keyringPath string, id string) (*openpgp.Entity, error) {
f, er := os.Open(keyringPath)
if er != nil {
return nil, er
}
defer f.Close()
entities, err := openpgp.ReadKeyRing(f)
if err != nil {
return nil, err
}
for _, entity := range entities {
switch {
case entity.PrivateKey == nil:
continue
case !entity.PrivateKey.Encrypted:
return entity, nil
default:
passphrase, err := PromptPassphrase(entity.PrivateKey)
if err == nil {
err = entity.PrivateKey.Decrypt(passphrase)
}
if err != nil {
fmt.Fprintf(os.Stderr, "could not decrypt private key: %s\n", err)
continue
}
return entity, nil
}
}
return nil, fmt.Errorf("no suitable private key found")
}
示例5: FetchEntity
func (fe *FileEntityFetcher) FetchEntity(keyId string) (*openpgp.Entity, error) {
f, err := wkfs.Open(fe.File)
if err != nil {
return nil, fmt.Errorf("jsonsign: FetchEntity: %v", err)
}
defer f.Close()
el, err := openpgp.ReadKeyRing(f)
if err != nil {
return nil, fmt.Errorf("jsonsign: openpgp.ReadKeyRing of %q: %v", fe.File, err)
}
for _, e := range el {
pubk := &e.PrivateKey.PublicKey
if pubk.KeyIdString() != keyId {
continue
}
if e.PrivateKey.Encrypted {
if err := fe.decryptEntity(e); err == nil {
return e, nil
} else {
return nil, err
}
}
return e, nil
}
return nil, fmt.Errorf("jsonsign: entity for keyid %q not found in %q", keyId, fe.File)
}
示例6: InitDocumentHandler
func InitDocumentHandler(defs UploadDefs) {
// initialize upload handling parameters
uploadPath = defs.Path
treshold = defs.ShareTreshold
// check for disabled secret sharing scheme
if treshold > 0 {
// compute prime: (2^512-1) - SharePrimeOfs
one := big.NewInt(1)
ofs := big.NewInt(int64(defs.SharePrimeOfs))
prime = new(big.Int).Lsh(one, 512)
prime = new(big.Int).Sub(prime, one)
prime = new(big.Int).Sub(prime, ofs)
// open keyring file
rdr, err := os.Open(defs.Keyring)
if err != nil {
// can't read keys -- terminate!
logger.Printf(logger.ERROR, "[sid.upload] Can't read keyring file '%s' -- terminating!\n", defs.Keyring)
os.Exit(1)
}
defer rdr.Close()
// read public keys from keyring
if reviewer, err = openpgp.ReadKeyRing(rdr); err != nil {
// can't read keys -- terminate!
logger.Printf(logger.ERROR, "[sid.upload] Failed to process keyring '%s' -- terminating!\n", defs.Keyring)
os.Exit(1)
}
} else {
logger.Printf(logger.WARN, "[sid.upload] Secret sharing scheme disabled -- uploads will be stored unencrypted!!")
}
}
示例7: runShowKey
func runShowKey(cmd *Command, args []string) {
var err error
log := NewTee("postcrypt")
path, _ := cmd.Config.GetString("main", "keyring")
if len(args) < 1 {
log.Err("too few arguments. run `go help " + cmd.Name + "`.")
return
}
// open gpg keyring file
fh, _ := os.Open(path)
if err != nil {
log.Crit("could not open keyring: " + err.Error())
return
}
// read keyring
keyring, err := openpgp.ReadKeyRing(fh)
if err != nil {
log.Crit("could not read keyring: " + err.Error())
return
}
for _, entity := range keyring {
if args[0] == getKeyId(entity) {
fmt.Printf("%s:\n", getKeyId(entity))
for _, ident := range entity.Identities {
fmt.Printf("\t%s\n", ident.Name)
}
}
}
}
示例8: findKey
func findKey(key string) (*openpgp.Entity, error) {
keyId, err := strconv.ParseUint(key, 16, 64)
if err != nil {
log.Printf("Unable to parse key '%s': %s\n", key, err)
return nil, &UnknownKey{key}
}
f, err := os.Open(KeyringFile)
if err != nil {
log.Printf("Failed to open keyring: %s\n", err)
return nil, err
}
defer f.Close()
el, err := openpgp.ReadKeyRing(f)
if err != nil {
log.Printf("Failed to read keyring: %s\n", err)
return nil, err
}
for _, entity := range el {
if entity.PrimaryKey.KeyId&0xFFFFFFFF == keyId {
return entity, nil
}
for _, key := range entity.Subkeys {
if key.PublicKey.KeyId&0xFFFFFFFF == keyId {
return entity, nil
}
}
}
return nil, &UnknownKey{key}
}
示例9: main
func main() {
sigReader := strings.NewReader(sig)
sigBlock, err := armor.Decode(sigReader)
if err != nil {
panic(err)
}
if sigBlock.Type != openpgp.SignatureType {
panic("not a signature type")
}
dataReader := strings.NewReader(data)
krfd, err := os.Open("/home/ulfr/.gnupg/pubring.gpg")
if err != nil {
panic(err)
}
defer krfd.Close()
keyring, err := openpgp.ReadKeyRing(krfd)
if err != nil {
panic(err)
}
entity, err := openpgp.CheckDetachedSignature(
keyring, dataReader, sigBlock.Body)
if err != nil {
panic(err)
}
fmt.Printf("valid signature from key %s\n",
hex.EncodeToString(entity.PrimaryKey.Fingerprint[:]))
}
示例10: Verify
// Verify() checks the validity of a signature for some data,
// and returns a boolean set to true if valid and an OpenPGP Entity
func Verify(data string, signature string, keyring io.Reader) (valid bool, entity *openpgp.Entity, err error) {
valid = false
// re-armor signature and transform into io.Reader
sigReader := strings.NewReader(reArmor(signature))
// decode armor
sigBlock, err := armor.Decode(sigReader)
if err != nil {
panic(err)
}
if sigBlock.Type != "PGP SIGNATURE" {
err = fmt.Errorf("Wrong signature type '%s'", sigBlock.Type)
panic(err)
}
// convert to io.Reader
srcReader := strings.NewReader(data)
// open the keyring
ring, err := openpgp.ReadKeyRing(keyring)
if err != nil {
panic(err)
}
entity, err = openpgp.CheckDetachedSignature(ring, srcReader, sigBlock.Body)
if err != nil {
panic(err)
}
// we passed, signature is valid
valid = true
return
}
示例11: processPublicKeyRing
func processPublicKeyRing() (entity *openpgp.Entity, entitylist openpgp.EntityList) {
// TODO: Handle a specified recipient
// Get default public keyring location
usr, err := user.Current()
if err != nil {
log.Fatal(err)
}
jaegerPublicKeyRing := fmt.Sprintf("%v/.gnupg/jaeger_pubring.gpg", usr.HomeDir)
publicKeyRing := ""
if _, err := os.Stat(jaegerPublicKeyRing); err == nil {
publicKeyRing = jaegerPublicKeyRing
} else {
publicKeyRing = fmt.Sprintf("%v/.gnupg/pubring.gpg", usr.HomeDir)
}
debug.Printf("publicKeyRing file:", publicKeyRing)
publicKeyRingBuffer, err := os.Open(publicKeyRing)
if err != nil {
panic(err)
}
entitylist, err = openpgp.ReadKeyRing(publicKeyRingBuffer)
if err != nil {
log.Fatal(err)
}
entity = entitylist[0]
debug.Printf("Public key default keyring:", entity.Identities)
return entity, entitylist
}
示例12: Sign
// Sign signs a string with a key identified by a key fingerprint or an email address
func Sign(data, keyid string, secringFile io.Reader) (sig string, err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("pgp.Sign(): %v", e)
}
}()
keyring, err := openpgp.ReadKeyRing(secringFile)
if err != nil {
err = fmt.Errorf("Keyring access failed: '%v'", err)
panic(err)
}
// find the entity in the keyring
var signer *openpgp.Entity
found := false
for _, entity := range keyring {
fingerprint := strings.ToUpper(hex.EncodeToString(entity.PrimaryKey.Fingerprint[:]))
for _, ident := range entity.Identities {
email := ident.UserId.Email
if keyid == fingerprint || keyid == email {
signer = entity
found = true
break
}
}
}
if !found {
err = fmt.Errorf("Signer '%s' not found", keyid)
panic(err)
}
// if private key is encrypted, attempt to decrypt it with the passphrase
if signer.PrivateKey.Encrypted {
// get private key passphrase
signer, err = decryptEntity(signer)
if err != nil {
panic(err)
}
}
// calculate signature
out := bytes.NewBuffer(nil)
message := bytes.NewBufferString(data)
err = openpgp.ArmoredDetachSign(out, signer, message, nil)
if err != nil {
err = fmt.Errorf("Signature failed: '%v'", err)
panic(err)
}
// convert the writer back to string
sig, err = deArmor(out.String())
if err != nil {
err = fmt.Errorf("Error converting signature to string: '%v'", err)
panic(err)
}
return
}
示例13: main
func main() {
if len(os.Args) < 2 {
fmt.Printf("usage:\t%s <FINGERPRINT>\nex: \t%s 02699C276B60F27FC55C329968D63477A392B6FA\n",
os.Args[0], os.Args[0])
os.Exit(1)
}
keyid := os.Args[1]
data := "some random string to sign"
secringFile, err := os.Open(FindHomedir() + "/.gnupg/secring.gpg")
if err != nil {
panic(err)
}
defer secringFile.Close()
keyring, err := openpgp.ReadKeyRing(secringFile)
if err != nil {
err = fmt.Errorf("Keyring access failed: '%v'", err)
panic(err)
}
// find the entity in the keyring
var signer *openpgp.Entity
found := false
for _, entity := range keyring {
fingerprint := strings.ToUpper(hex.EncodeToString(entity.PrimaryKey.Fingerprint[:]))
fmt.Println("reading key with fingerprint", fingerprint)
if keyid == fingerprint {
signer = entity
found = true
fmt.Println("found a match")
break
}
}
if !found {
err = fmt.Errorf("No key found for ID '%s'", keyid)
panic(err)
}
// if private key is encrypted, attempt to decrypt it with the cached passphrase
// then try with an agent or by asking the user for a passphrase
if signer.PrivateKey.Encrypted {
// get private key passphrase
signer, err = decryptEntity(signer)
if err != nil {
panic(err)
}
}
// calculate signature
out := bytes.NewBuffer(nil)
message := bytes.NewBufferString(data)
err = openpgp.ArmoredDetachSign(out, signer, message, nil)
if err != nil {
err = fmt.Errorf("Signature failed: '%v'", err)
panic(err)
}
fmt.Printf("%s\n", out)
}
示例14: decrypt
func decrypt(ringPath string, input io.Reader) (io.Reader, error) {
ringFile, err := os.Open(ringPath)
if err != nil {
return nil, err
}
defer ringFile.Close()
ring, err := openpgp.ReadKeyRing(ringFile)
if err != nil {
return nil, err
}
var keyToTry, attempt int
var triedCache bool
promptFunc := openpgp.PromptFunction(func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
if keyToTry >= len(keys) {
return nil, fmt.Errorf("no more keys to try")
}
if attempt > 2 {
attempt = 0
keyToTry++
return nil, nil
}
defer func() { attempt++ }()
key := keys[keyToTry]
fingerprint := fmt.Sprintf("%X", key.PublicKey.Fingerprint)
if !triedCache {
triedCache = true
if cachedPass, _ := passphrase.GetPassphrase(fingerprint, "", "", "", false, false); cachedPass != "" {
if err := key.PrivateKey.Decrypt([]byte(cachedPass)); err == nil {
return nil, nil
}
}
}
passphrase.ClearCachedPassphrase(fingerprint)
prompt := ""
description := fmt.Sprintf("Key %s; attempt %d", key.PublicKey.KeyIdShortString(), attempt+1)
passwd, err := passphrase.GetPassphrase(fingerprint, prompt, description, "", true, false)
if err != nil {
return nil, err
}
key.PrivateKey.Decrypt([]byte(passwd))
return nil, nil
})
msgDetails, err := openpgp.ReadMessage(input, ring, promptFunc, nil)
if err != nil {
return nil, err
}
return msgDetails.UnverifiedBody, nil
}
示例15: checkGPG
func checkGPG(file File) (state SigState, err error) {
var signer *openpgp.Entity
keypath := path.Join(os.Getenv("HOME"), "/.gnupg/pubring.gpg")
keys, err := os.Open(keypath)
if err != nil {
fmt.Printf("Could not open public keyring at %s\n", keypath)
os.Exit(2)
}
keyring, err := openpgp.ReadKeyRing(keys)
if err != nil {
fmt.Printf("Error reading public keyring: %s\n", err)
os.Exit(2)
}
if *flagBin {
signer, err = openpgp.CheckDetachedSignature(keyring, bytes.NewReader(file.content), bytes.NewReader(file.signature))
} else {
signer, err = openpgp.CheckArmoredDetachedSignature(keyring, bytes.NewReader(file.content), bytes.NewReader(file.signature))
}
if err != nil {
fmt.Printf("Invalid signature or public key not present: %s\n", err)
os.Exit(2)
}
state.sig = signer.PrimaryKey.KeyIdString()
l := len(*flagKeyid)
if l > 0 {
var rid string
// Force the local id to be all uppercase
lid := strings.ToUpper(*flagKeyid)
// check the number of chars on the remote id to see if it's a
// short or long id. If it's not 8 or 16, it's not valid.
switch l {
case 8:
rid = signer.PrimaryKey.KeyIdShortString()
case 16:
rid = signer.PrimaryKey.KeyIdString()
}
if len(rid) == 0 {
fmt.Printf("You did not specify a valid GPG keyid length. Must be 8 or 16 characters.")
os.Exit(2)
}
if lid != rid {
fmt.Printf("The remote file was not signed by the expected GPG Public key. Expected %s and got %s\n", lid, rid)
os.Exit(2)
}
}
state.success = true
return state, nil
}