package go_pgp import ( "bytes" "io" "os" // required in order to use the crypto.SHA256- and -SHA512-Hashes _ "crypto/sha256" _ "crypto/sha512" "github.com/ProtonMail/go-crypto/openpgp" "github.com/ProtonMail/go-crypto/openpgp/armor" ) func writeKeyDataToFile(data []byte, filePath, dataType string, armored bool) error { out, err := os.Create(filePath) if nil != err { return err } defer out.Close() if !armored { _, err = out.Write(data) if nil == err { out.Sync() } } else { var armored io.WriteCloser armored, err = armor.Encode(out, dataType, nil) if nil != err { return err } _, err = armored.Write(data) if nil == err { armored.Close() out.Sync() } } return err } // WritePublicEntityData will write the entitys complete public data to a file func WritePublicEntityData(entity *Entity, filePath string) error { data, err := ExtractPublicEntityData(entity) if nil != err { return err } return writeKeyDataToFile(data, filePath, openpgp.PublicKeyType, false) } // WriteArmoredPublicEntityData will write the entitys complete public data to an armored file func WriteArmoredPublicEntityData(entity *Entity, filePath string) error { data, err := ExtractPublicEntityData(entity) if nil != err { return err } return writeKeyDataToFile(data, filePath, openpgp.PublicKeyType, true) } // WritePrivateEntityData will write the entitys public and private keys to a file func WritePrivateEntityData(entity *Entity, filePath string) error { data, err := ExtractPrivateEntityData(entity) if nil != err { return err } return writeKeyDataToFile(data, filePath, openpgp.PrivateKeyType, false) } // WriteArmoredPrivateEntityData will write the entitys public and private keys to an armored file func WriteArmoredPrivateEntityData(entity *Entity, filePath string) error { data, err := ExtractPrivateEntityData(entity) if nil != err { return err } return writeKeyDataToFile(data, filePath, openpgp.PrivateKeyType, true) } // ExtractPublicEntityData will write the entitys complete public data to a []byte func ExtractPublicEntityData(entity *Entity) ([]byte, error) { if nil == entity { return nil, ErrUndefinedPGPEntity } out := new(bytes.Buffer) entity.Serialize(out) return out.Bytes(), nil } // ExtractPrivateEntityData will write the entitys public and private keys to a []byte func ExtractPrivateEntityData(entity *Entity) ([]byte, error) { if nil == entity { return nil, ErrUndefinedPGPEntity } out := new(bytes.Buffer) entity.SerializePrivate(out, &defaultConfig) return out.Bytes(), nil }