func (s *SftpSession) DecryptFile(fname string) (string, error) { lr, err := os.Open(fname) if err != nil { return "", err } defer lr.Close() /* slurped, err := ioutil.ReadAll(lr) if err != nil { return "", err } */ fdecrypted := strings.TrimSuffix(fname, filepath.Ext(fname)) lw, err := os.Create(fdecrypted) if err != nil { return "", fmt.Errorf("open file error: %s, %s\n", fdecrypted, err.Error()) } var armorStart = []byte("-----BEGIN ") var msg *openpgp.MessageDetails var dcrypterr error buf := bufio.NewReaderSize(lr, 512) peek, err := buf.Peek(15) if err != nil { return "", fmt.Errorf("armor peek: %s, %s\n", fdecrypted, dcrypterr.Error()) } if bytes.HasPrefix(peek, armorStart) { // armored log.Printf("armored: %s\n", fname) // try reading in an armored block dearmor, err := armor.Decode(buf) if err != nil { log.Printf("not armored: %s\n", fname) return "", fmt.Errorf("armor read msg error: %s, %s\n", fdecrypted, dcrypterr.Error()) } else { log.Printf("armored: %s\n", fname) // Decrypt the dearmored message msg, dcrypterr = openpgp.ReadMessage(dearmor.Body, s.entityList, nil, nil) } } else { // Decrypt the binary message msg, dcrypterr = openpgp.ReadMessage(buf, s.entityList, nil, nil) } if dcrypterr != nil { return "", fmt.Errorf("decrypt read msg error: %s, %s\n", fdecrypted, dcrypterr.Error()) } _, err = io.Copy(lw, msg.UnverifiedBody) if err != nil { return "", err } return fdecrypted, nil }
// Initialize a new DefinitionManager // The definition manager is responsible for downloading the main.cvd and daily.cvd from // the URLs defined above, via conditional (ETAG) requests // In addiiton it holds the state of the download (ETAGS and signature, once verification is done) func NewDefinitionManager() (*DefinitionsManager, error) { // new instance of the manager manager := new(DefinitionsManager) // open the public key file verificationKeyFileReader, err := os.Open("verification.key") if err != nil { return nil, err } // close the file once we are done here defer verificationKeyFileReader.Close() // instantiate a new File Reader keyReader := bufio.NewReader(verificationKeyFileReader) // if we got here then the sha256 match, we can proceed block, err := armor.Decode(keyReader) if err != nil { return nil, err } manager.PublicKeyData = block manager.httpCLient = http.Client{} return manager, nil }
func (s *SamplePacketSuite) TestPacketCounts(c *gc.C) { testCases := []struct { name string nUserID, nUserAttribute, nSubKey, nSignature int }{{ "0ff16c87.asc", 9, 0, 1, 0, }, { "alice_signed.asc", 1, 0, 1, 0, }, { "uat.asc", 2, 1, 3, 0, }, { "252B8B37.dupsig.asc", 3, 0, 2, 1, }} for i, testCase := range testCases { c.Logf("test#%d: %s", i, testCase.name) f := testing.MustInput(testCase.name) defer f.Close() block, err := armor.Decode(f) c.Assert(err, gc.IsNil) var key *PrimaryKey for keyRead := range ReadKeys(block.Body) { key = keyRead.PrimaryKey } c.Assert(key, gc.NotNil) c.Assert(key.UserIDs, gc.HasLen, testCase.nUserID) c.Assert(key.UserAttributes, gc.HasLen, testCase.nUserAttribute) c.Assert(key.SubKeys, gc.HasLen, testCase.nSubKey) c.Assert(key.Signatures, gc.HasLen, testCase.nSignature) } }
func v3KeyReader(t *testing.T) io.Reader { armorBlock, err := armor.Decode(bytes.NewBufferString(keySigV3Armor)) if err != nil { t.Fatalf("armor Decode failed: %v", err) } return armorBlock.Body }
func (vr *VerifyRequest) VerifySignature() bool { armorData := reArmor(vr.CamliSig) block, _ := armor.Decode(bytes.NewBufferString(armorData)) if block == nil { return vr.fail("can't parse camliSig armor") } var p packet.Packet var err error p, err = packet.Read(block.Body) if err != nil { return vr.fail("error reading PGP packet from camliSig: " + err.Error()) } sig, ok := p.(*packet.Signature) if !ok { return vr.fail("PGP packet isn't a signature packet") } if sig.Hash != crypto.SHA1 && sig.Hash != crypto.SHA256 { return vr.fail("I can only verify SHA1 or SHA256 signatures") } if sig.SigType != packet.SigTypeBinary { return vr.fail("I can only verify binary signatures") } hash := sig.Hash.New() hash.Write(vr.bp) // payload bytes err = vr.PublicKeyPacket.VerifySignature(hash, sig) if err != nil { return vr.fail(fmt.Sprintf("bad signature: %s", err)) } vr.SignerKeyId = vr.PublicKeyPacket.KeyIdString() return true }
func GpgDecrypt(text2decrypt string) string { encrypted := bytes.NewBuffer([]byte(text2decrypt)) bin_encrypt, err := armor.Decode(encrypted) if err != nil { log.Printf("[PGP] not an armored payload: %s", err.Error()) return "" } cleartext_md, err := openpgp.ReadMessage(bin_encrypt.Body, nil, func(keys []openpgp.Key, symmetric bool) ([]byte, error) { return []byte(config.GetTribeID()), nil }, nil) if err != nil { log.Printf("[PGP] Can't decrypt payload: %s", err.Error()) return "" } plaintext, err := ioutil.ReadAll(cleartext_md.UnverifiedBody) if err != nil { log.Printf("[PGP] Can't read cleartext: %s", err.Error()) return "" } return string(plaintext) }
func trySig(filename string) (bool, error) { sigFile, err := os.Open(filename) if err != nil { return true, err } defer sigFile.Close() b, err := armor.Decode(sigFile) if err != nil && err != io.EOF { return true, err } if b == nil { return false, nil } // Read the signature file pack, err := packet.Read(b.Body) if err != nil { return true, err } // Was it really a signature file ? If yes, get the Signature if signature, ok := pack.(*packet.Signature); !ok { return false, nil } else { fmt.Printf("Signature made %s\n", signature.CreationTime.Format(time.RFC3339)) // Signature made Wed 05 Aug 2015 11:48:13 PM UTC using RSA key ID F553000C // Primary key fingerprint: EF64 BCCB 58BC F501 FEDA 0582 0581 2930 F553 000C // binary signature, digest algorithm SHA256 return true, nil } }
func decryptString(decryptionString string, encryptionPassphraseString string) (string, error) { encryptionPassphrase := []byte(encryptionPassphraseString) decbuf := bytes.NewBuffer([]byte(decryptionString)) result, err := armor.Decode(decbuf) if err != nil { return "", err } alreadyPrompted := false md, err := openpgp.ReadMessage(result.Body, nil, func(keys []openpgp.Key, symmetric bool) ([]byte, error) { if alreadyPrompted { return nil, errors.New("Could not decrypt using passphrase") } else { alreadyPrompted = true } return encryptionPassphrase, nil }, nil) if err != nil { return "", err } bytes, err := ioutil.ReadAll(md.UnverifiedBody) if err != nil { return "", err } return string(bytes), nil }
func ReadArmorKeys(r io.Reader) (PrimaryKeyChan, error) { block, err := armor.Decode(r) if err != nil { return nil, err } return ReadKeys(block.Body), nil }
func decryptOpenpgp(data io.Reader, gpghome string, pass []byte) (io.Reader, error) { privkeyfile, err := os.Open(fmt.Sprintf("%s%ssecring.gpg", gpghome, string(os.PathSeparator))) if err != nil { fmt.Println("Failed to open secring", err) return nil, err } privring, err := openpgp.ReadKeyRing(privkeyfile) if err != nil { fmt.Println("Failed to open secring", err) return nil, err } //reader := bytes.NewReader(data) //brk,_ := ioutil.ReadAll(data) //fmt.Println("wtf",string(brk)) //fmt.Println("here is where eof panic") block, err := armor.Decode(data) if err != nil { fmt.Println(err) panic(err) } if len(pass) == 0 { fmt.Fprintf(os.Stderr, "Password: "******"") } for _, entity := range privring { if entity.PrivateKey != nil && entity.PrivateKey.Encrypted { entity.PrivateKey.Decrypt(pass) } for _, subkey := range entity.Subkeys { if subkey.PrivateKey != nil && subkey.PrivateKey.Encrypted { subkey.PrivateKey.Decrypt(pass) } } } md, err := openpgp.ReadMessage(block.Body, privring, nil, nil) if err != nil { return nil, err } return md.UnverifiedBody, nil //plaintext, err := ioutil.ReadAll(md.UnverifiedBody) //if err != nil { // panic(err) // } // return plaintext, nil }
func TestKeyserverHKP(t *testing.T) { kss, caPool, clks, _, ck, clientConfig, teardown := setupRealm(t, 1, 0) ks := kss[0] defer teardown() stop := stoppableSyncedClocks(clks) defer close(stop) waitForFirstEpoch(kss[0], clientConfig.Realms[0].VerificationPolicy.GetQuorum()) clientTLS, err := clientConfig.Realms[0].ClientTLS.Config(ck) if err != nil { t.Fatal(err) } pgpKeyRef := []byte("this-is-alices-pgp-key") doRegister(t, ks, clientConfig, clientTLS, caPool, clks[0].Now(), alice, 0, proto.Profile{ Nonce: []byte("definitely used only once"), Keys: map[string][]byte{"pgp": pgpKeyRef}, }) tr := &http.Transport{ // TODO: identify and fix the bug with client auth and HTTP/2 and use clientTLS // Also set HKPTLS back to proto.REQUIRE_AND_VERIFY_CLIENT_CERT TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //TLSClientConfig: clientTLS, } url := "https://" + ks.hkpListen.Addr().String() + "/pks/lookup?op=get&search=" + alice c := &http.Client{Transport: tr} resp, err := c.Get(url) if err != nil { t.Fatal(err) } defer resp.Body.Close() if resp.Status != "200 OK" { b, e := ioutil.ReadAll(resp.Body) t.Fatalf("%s (%s)", b, e) } pgpBlock, err := armor.Decode(resp.Body) if err != nil { t.Fatal(err) } if got, want := pgpBlock.Type, "PGP PUBLIC KEY BLOCK"; got != want { t.Errorf("pgpBlock.Type: got %v but wanted %v", got, want) } if got, want := len(pgpBlock.Header), 0; got != want { t.Errorf("len(pgpBlock.Header): got %v but wanted %v", got, want) } pgpKey, err := ioutil.ReadAll(pgpBlock.Body) if err != nil { t.Fatal(err) } if got, want := pgpKey, pgpKeyRef; !bytes.Equal(got, want) { t.Errorf("pgpKey: got %q but wanted %q", got, want) } }
// KeyRing reads a openpgp.KeyRing from the given io.Reader which may then be // used to validate GPG keys in RPM packages. func KeyRing(r io.Reader) (openpgp.KeyRing, error) { // decode gpgkey file p, err := armor.Decode(r) if err != nil { return nil, err } // extract keys return openpgp.ReadKeyRing(p.Body) }
func PublicKeyToPGPClient(publicKey string) PGPClient { block, err := armor.Decode(strings.NewReader(publicKey)) if err != nil { panic(err) } entity, err := openpgp.ReadEntity(packet.NewReader(block.Body)) if err != nil { panic(err) } return PGPClient{openpgp.EntityList{entity}} }
func DecodeArmor(armorStr string) (blockType string, headers map[string]string, data []byte, err error) { buf := bytes.NewBufferString(armorStr) block, err := armor.Decode(buf) if err != nil { return "", nil, nil, err } data, err = ioutil.ReadAll(block.Body) if err != nil { return "", nil, nil, err } return block.Type, block.Header, data, nil }
func (s *SamplePacketSuite) TestDeduplicate(c *gc.C) { f := testing.MustInput("d7346e26.asc") defer f.Close() block, err := armor.Decode(f) if err != nil { c.Fatal(err) } // Parse keyring, duplicate all packet types except primary pubkey. kr := &OpaqueKeyring{} for opkr := range ReadOpaqueKeyrings(block.Body) { c.Assert(opkr.Error, gc.IsNil) for _, op := range opkr.Packets { kr.Packets = append(kr.Packets, op) switch op.Tag { case 2: kr.Packets = append(kr.Packets, op) fallthrough case 13, 14, 17: kr.Packets = append(kr.Packets, op) } } } key, err := kr.Parse() c.Assert(err, gc.IsNil) n := 0 for _, node := range key.contents() { c.Logf("%s", node.uuid()) n++ } c.Log() err = CollectDuplicates(key) c.Assert(err, gc.IsNil) n2 := 0 for _, node := range key.contents() { c.Logf("%s %d", node.uuid(), node.packet().Count) n2++ switch node.packet().Tag { case 2: c.Check(node.packet().Count, gc.Equals, 2) case 13, 14, 17: c.Check(node.packet().Count, gc.Equals, 1) case 6: c.Check(node.packet().Count, gc.Equals, 0) default: c.Fatal("should not happen") } } c.Assert(n2 < n, gc.Equals, true) }
// readArmored reads an armored block with the given type. func readArmored(r io.Reader, expectedType string) (body io.Reader, err error) { block, err := armor.Decode(r) if err != nil { return } if block.Type != expectedType { return nil, errors.InvalidArgumentError("expected '" + expectedType + "', got: " + block.Type) } return block.Body, nil }
func TestKeyserverHKP(t *testing.T) { kss, caPool, clks, _, ck, clientConfig, teardown := setupRealm(t, 1, 0) ks := kss[0] defer teardown() stop := stoppableSyncedClocks(clks) defer close(stop) waitForFirstEpoch(kss[0], clientConfig.Realms[0].VerificationPolicy.Quorum) clientTLS, err := clientConfig.Realms[0].ClientTLS.Config(ck) if err != nil { t.Fatal(err) } pgpKeyRef := []byte("this-is-alices-pgp-key") doUpdate(t, ks, clientConfig, clientTLS, caPool, clks[0].Now(), alice, 0, proto.Profile{ Nonce: []byte("definitely used only once"), Keys: map[string][]byte{"pgp": pgpKeyRef}, }) c := &http.Client{Transport: &http.Transport{ TLSClientConfig: clientTLS, }} url := "https://" + ks.hkpListen.Addr().String() + "/pks/lookup?op=get&search=" + alice resp, err := c.Get(url) if err != nil { t.Fatal(err) } defer resp.Body.Close() if resp.Status != "200 OK" { b, e := ioutil.ReadAll(resp.Body) t.Fatalf("%s (%s)", b, e) } pgpBlock, err := armor.Decode(resp.Body) if err != nil { t.Fatal(err) } if got, want := pgpBlock.Type, "PGP PUBLIC KEY BLOCK"; got != want { t.Error("pgpBlock.Type: got %v but wanted %v", got, want) } if got, want := len(pgpBlock.Header), 0; got != want { t.Error("len(pgpBlock.Header): got %v but wanted %v", got, want) } pgpKey, err := ioutil.ReadAll(pgpBlock.Body) if err != nil { t.Fatal(err) } if got, want := pgpKey, pgpKeyRef; !bytes.Equal(got, want) { t.Error("pgpKey: got %q but wanted %q", got, want) } }
// DecryptDataArmored decrypts armored data using OpenPGP decryption. func DecryptDataArmored(input []byte, password string) []byte { inputReader := bytes.NewReader(input) block, err := armor.Decode(inputReader) PanicIfErr(err) armorReader := block.Body unarmoredInput, err := ioutil.ReadAll(armorReader) PanicIfErr(err) return DecryptData(unarmoredInput, password) }
// Decode an ASCII armored message. It returns the decoded bytes, the message type as mentioned in // the header "-----BEGIN <MESSAGE TYPE>-----" and footer "-----END <MESSAGE TYPE>-----". func AsciiArmorDecode(s []byte) ([]byte, string, map[string]string, error) { in := bytes.NewBuffer(s) block, err := armor.Decode(in) if err != nil { return nil, "", nil, fmt.Errorf("Failed to read ASCII armored data: %s", err) } data, err := ioutil.ReadAll(block.Body) if err != nil { return nil, "", nil, fmt.Errorf("Failed to read ASCII armored data: %s", err) } return data, block.Type, block.Header, nil }
// ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file. func ReadArmoredKeyRing(r io.Reader) (EntityList, error) { block, err := armor.Decode(r) if err == io.EOF { return nil, errors.InvalidArgumentError("no armored data found") } if err != nil { return nil, err } if block.Type != PublicKeyType && block.Type != PrivateKeyType { return nil, errors.InvalidArgumentError("expected public or private key block, got: " + block.Type) } return ReadKeyRing(block.Body) }
// GetPublicKey converts an ASCII-armored public key representation // into an OpenPGP key. func GetPublicKey(buf []byte) (*packet.PublicKey, error) { keyRdr, err := armor.Decode(bytes.NewBuffer(buf)) if err != nil { return nil, err } keyData, err := packet.Read(keyRdr.Body) if err != nil { return nil, err } key, ok := keyData.(*packet.PublicKey) if !ok { return nil, errors.New("Invalid public key") } return key, nil }
func GpgGetHeaders(text2decrypt string) map[string]string { encrypted := bytes.NewBuffer([]byte(text2decrypt)) var tmp_map map[string]string tmp_map = make(map[string]string) bin_encrypt, err := armor.Decode(encrypted) if err != nil { log.Printf("[PGP] not an armored payload: %s", err.Error()) tmp_map["Command"] = "NOOP" return tmp_map } return bin_encrypt.Header }
func encryptEmail(e *Email) error { if len(e.OpenPGPEncryptTo) == 0 { return nil } buf := &bytes.Buffer{} var destEntities []*openpgp.Entity for _, eto := range e.OpenPGPEncryptTo { r := bytes.NewBufferString(eto) blk, err := armor.Decode(r) if err != nil { return err } rr := packet.NewReader(blk.Body) e, err := openpgp.ReadEntity(rr) if err != nil { return err } destEntities = append(destEntities, e) } aew, err := armor.Encode(buf, "PGP MESSAGE", map[string]string{ "Version": "OpenPGP", }) if err != nil { return err } wr, err := openpgp.Encrypt(aew, destEntities, nil, nil, nil) if err != nil { return err } _, err = wr.Write([]byte(e.Body)) if err != nil { wr.Close() return err } wr.Close() aew.Close() e.Body = string(buf.Bytes()) return nil }
func parsePubKey(r io.Reader) (*packet.PublicKey, error) { block, _ := armor.Decode(r) if block == nil { return nil, errors.New("can't parse armor") } var p packet.Packet var err error p, err = packet.Read(block.Body) if err != nil { return nil, err } pk, ok := p.(*packet.PublicKey) if !ok { return nil, errors.New("PGP packet isn't a public key") } return pk, nil }
// Decrypt uses PGP to obtain the data key from the EncryptedKey store in the MasterKey and returns it func (key *MasterKey) Decrypt() ([]byte, error) { ring, err := key.secRing() if err != nil { return nil, fmt.Errorf("Could not load secring: %s", err) } block, err := armor.Decode(strings.NewReader(key.EncryptedKey)) if err != nil { return nil, fmt.Errorf("Armor decoding failed: %s", err) } md, err := openpgp.ReadMessage(block.Body, ring, key.passphrasePrompt, nil) if err != nil { return nil, fmt.Errorf("Reading PGP message failed: %s", err) } if b, err := ioutil.ReadAll(md.UnverifiedBody); err == nil { return b, nil } return nil, fmt.Errorf("The key could not be decrypted with any of the GPG entries") }
// Decrypt decrypt an encrypted message func (g *Gpg) Decrypt(blob []byte) ([]byte, error) { // Open the private key file privateRingBuffer, err := os.Open(g.PrivateKeyring) if err != nil { return nil, err } defer privateRingBuffer.Close() privateRing, err := openpgp.ReadKeyRing(privateRingBuffer) if err != nil { return nil, err } privateKey := getKeyByEmail(privateRing, g.Email) fmt.Print("GPG Passphrase: ") passphrase, err := terminal.ReadPassword(0) fmt.Println("") log.Printf("[DEBUG] GPG Decrypting private key using passphrase") //passphraseByte := []byte(passphrase) privateKey.PrivateKey.Decrypt(passphrase) for _, subkey := range privateKey.Subkeys { subkey.PrivateKey.Decrypt(passphrase) } log.Printf("[DEBUG] GPG Finished decrypting private key using passphrase") armoredBlock, err := armor.Decode(bytes.NewReader(blob)) if err != nil { return nil, err } // Decrypt it with the contents of the private key md, err := openpgp.ReadMessage(armoredBlock.Body, privateRing, nil, nil) if err != nil { return nil, fmt.Errorf("GPG Read message failed: %v", err) } plain, err := ioutil.ReadAll(md.UnverifiedBody) if err != nil { return nil, err } return plain, nil }
func printMessage() { decbuf := bytes.NewBuffer([]byte(encryptedMessage)) result, err := armor.Decode(decbuf) if err != nil { log.Fatal(err) } md, err := openpgp.ReadMessage(result.Body, nil, func(keys []openpgp.Key, symmetric bool) ([]byte, error) { return []byte("golang"), nil }, nil) if err != nil { log.Fatal(err) } fmt.Println("dec version:", result.Header["Version"]) fmt.Println("dec type:", result.Type) bytes, err := ioutil.ReadAll(md.UnverifiedBody) fmt.Println("md:", string(bytes)) }
func Verify(payload string, signature []byte, pubkey *packet.PublicKey) error { // decode and read the signature block, err := armor.Decode(bytes.NewBuffer(signature)) if err != nil { return err } pkt, err := packet.Read(block.Body) if err != nil { return err } sig, ok := pkt.(*packet.Signature) if !ok { return fmt.Errorf("could not parse the signature") } if sig.Hash != crypto.SHA256 || sig.Hash != crypto.SHA512 { return fmt.Errorf("was not a SHA-256 or SHA-512 signature") } if sig.SigType != packet.SigTypeBinary { return fmt.Errorf("was not a binary signature") } // verify the signature hash := sig.Hash.New() _, err = hash.Write([]byte(payload)) if err != nil { return err } err = pubkey.VerifySignature(hash, sig) if err != nil { return err } return nil }
func (o *openPGP) SetKey(k key) (err error) { keyPath := filepath.Join(conf.mountPoint, k.Path) keyFile, err := os.Open(keyPath) if err != nil { return } defer keyFile.Close() keyBlock, err := armor.Decode(keyFile) if err != nil { return } reader := packet.NewReader(keyBlock.Body) entity, err := openpgp.ReadEntity(reader) if err != nil { return } switch keyBlock.Type { case openpgp.PrivateKeyType: if k.Private != true { return fmt.Errorf("public key detected in private key slot") } o.secKey = entity case openpgp.PublicKeyType: if k.Private == true { return fmt.Errorf("private key detected in public key slot") } o.pubKey = entity default: return fmt.Errorf("key type error: %s", keyBlock.Type) } return }
func main() { b, err := armor.Decode(p512Key) if err != nil { log.Fatal(err) } // p, err := ioutil.ReadAll(b.Body) // if err != nil { // log.Fatal(err) // } // for i := range p { // fmt.Printf("%#02x, ", p[i]) // } p, err := packet.Read(b.Body) if err != nil { log.Fatal(err) } if p, ok := p.(*packet.PrivateKey); ok { log.Println(p.PublicKey.PubKeyAlgo) } }