Skip to content

PGP Encrypt & Decrypt — Go source

Encrypt or decrypt messages with PGP public/private keys. Powered by OpenPGP.js, runs entirely in your browser.

This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Package pgpencrypt is the Go twin of CosmoDev's src/lib/pgp-encrypt.ts
// (dual source: the web lib is TypeScript, the CLI lib is Go — kept in
// lock-step). Pure logic, never panics — invalid input returns errors.
// The table-driven tests in pgp_encrypt_test.go share vectors with
// src/lib/pgp-encrypt.test.ts so the two implementations are held to the
// same contract.
//
// The TS lib is built on OpenPGP.js; Go's stdlib has no OpenPGP support,
// so the twin uses github.com/ProtonMail/go-crypto/openpgp — the
// maintained successor of golang.org/x/crypto/openpgp — to mirror the
// same surface: readKeyInfo / pgpEncrypt / pgpDecrypt over ASCII-armored
// keys and messages.
package pgpencrypt

import (
	"bytes"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"sort"
	"strings"
	"time"

	"github.com/ProtonMail/go-crypto/openpgp"
	"github.com/ProtonMail/go-crypto/openpgp/armor"
	"github.com/ProtonMail/go-crypto/openpgp/packet"
)

// PGPKeyInfo mirrors PGPKeyInfo in src/lib/pgp-encrypt.ts: metadata
// extracted from an armored public or private key.
type PGPKeyInfo struct {
	UserID       string  // first user ID, or "unknown"
	Fingerprint  string  // uppercase 40-hex (v4) fingerprint
	Algorithm    string  // openpgp.js-style algorithm name, e.g. "rsaEncryptSign"
	CreationDate string  // "YYYY-MM-DD" (UTC)
	Expiry       *string // "YYYY-MM-DD", nil when the key never expires
	IsPrivate    bool    // detected from the armor header
}

// algorithmName maps a packet.PublicKeyAlgorithm to the openpgp.js
// algorithm string reported by getAlgorithmInfo().algorithm, so both
// twins return the same names for the same keys.
func algorithmName(algo packet.PublicKeyAlgorithm) string {
	switch algo {
	case packet.PubKeyAlgoRSA:
		return "rsaEncryptSign"
	case packet.PubKeyAlgoRSAEncryptOnly:
		return "rsaEncrypt"
	case packet.PubKeyAlgoRSASignOnly:
		return "rsaSign"
	case packet.PubKeyAlgoElGamal:
		return "elgamal"
	case packet.PubKeyAlgoDSA:
		return "dsa"
	case packet.PubKeyAlgoECDH:
		return "ecdh"
	case packet.PubKeyAlgoEdDSA:
		return "eddsa"
	default:
		return fmt.Sprintf("unknown(%d)", int(algo))
	}
}

// readEntity parses a single armored (public or private) key into an
// openpgp.Entity.
func readEntity(armoredKey string) (*openpgp.Entity, error) {
	block, err := armor.Decode(strings.NewReader(armoredKey))
	if err != nil {
		return nil, err
	}
	return openpgp.ReadEntity(packet.NewReader(block.Body))
}

// ReadKeyInfo reads a PGP key (public or private) and extracts its
// metadata. It is the twin of readKeyInfo() in src/lib/pgp-encrypt.ts
// and throws-equivalent: an error is returned for invalid or
// unrecognized key material.
func ReadKeyInfo(armoredKey string) (PGPKeyInfo, error) {
	if armoredKey == "" {
		return PGPKeyInfo{}, errors.New("Key input is empty or invalid.")
	}

	trimmed := strings.TrimSpace(armoredKey)

	// Detect key type from armor header (mirrors the TS lib).
	isPrivateKey := strings.Contains(trimmed, "-----BEGIN PGP PRIVATE KEY BLOCK-----") ||
		strings.Contains(trimmed, "-----BEGIN PGP SECRET KEY BLOCK-----")

	entity, err := readEntity(trimmed)
	if err != nil {
		return PGPKeyInfo{}, fmt.Errorf("Invalid PGP key: %v", err)
	}

	// First user ID by sorted identity key — map iteration order is random
	// in Go, while the TS lib takes getUserIDs()[0].
	ids := make([]string, 0, len(entity.Identities))
	for id := range entity.Identities {
		ids = append(ids, id)
	}
	sort.Strings(ids)
	userID := "unknown"
	if len(ids) > 0 {
		userID = ids[0]
	}

	pk := entity.PrimaryKey
	info := PGPKeyInfo{
		UserID:       userID,
		Fingerprint:  strings.ToUpper(hex.EncodeToString(pk.Fingerprint[:])),
		Algorithm:    algorithmName(pk.PubKeyAlgo),
		CreationDate: pk.CreationTime.UTC().Format("2006-01-02"),
		IsPrivate:    isPrivateKey,
	}
	// go-crypto keeps the primary-key lifetime on the primary identity's
	// self-signature (KeyLifetimeSecs *uint32); openpgp.js surfaces the same
	// value via getExpirationTime().
	if id := entity.PrimaryIdentity(); id != nil && id.SelfSignature != nil && id.SelfSignature.KeyLifetimeSecs != nil {
		expiry := pk.CreationTime.
			Add(time.Duration(*id.SelfSignature.KeyLifetimeSecs) * time.Second).
			UTC().Format("2006-01-02")
		info.Expiry = &expiry
	}
	return info, nil
}

// unlockPrivateKey decrypts an encrypted private key's secret material
// with the passphrase (primary key + subkeys). The twin of openpgp.js's
// decryptKey().
func unlockPrivateKey(entity *openpgp.Entity, passphrase string) error {
	if entity.PrivateKey != nil && entity.PrivateKey.Encrypted {
		if err := entity.PrivateKey.Decrypt([]byte(passphrase)); err != nil {
			return err
		}
	}
	for _, sub := range entity.Subkeys {
		if sub.PrivateKey != nil && sub.PrivateKey.Encrypted {
			if err := sub.PrivateKey.Decrypt([]byte(passphrase)); err != nil {
				return err
			}
		}
	}
	return nil
}

// PgpEncrypt encrypts a plaintext message for a recipient's public key
// and returns an ASCII-armored PGP message. It is the twin of
// pgpEncrypt() in src/lib/pgp-encrypt.ts; an empty signingPrivateKeyArmored
// means "do not sign" (the TS optional parameter's zero-value default).
func PgpEncrypt(message, publicKeyArmored, signingPrivateKeyArmored, passphrase string) (string, error) {
	if message == "" {
		return "", errors.New("Message must not be empty.")
	}
	if publicKeyArmored == "" {
		return "", errors.New("Recipient public key must not be empty.")
	}

	to, err := readEntity(strings.TrimSpace(publicKeyArmored))
	if err != nil {
		return "", err
	}

	var signer *openpgp.Entity
	if signingPrivateKeyArmored != "" {
		signer, err = readEntity(strings.TrimSpace(signingPrivateKeyArmored))
		if err != nil {
			return "", err
		}
		if passphrase != "" {
			if err := unlockPrivateKey(signer, passphrase); err != nil {
				return "", err
			}
		}
	}

	var buf bytes.Buffer
	armorWriter, err := armor.Encode(&buf, "PGP MESSAGE", nil)
	if err != nil {
		return "", err
	}
	plaintextWriter, err := openpgp.Encrypt(armorWriter, []*openpgp.Entity{to}, signer, nil, nil)
	if err != nil {
		return "", err
	}
	if _, err := plaintextWriter.Write([]byte(message)); err != nil {
		return "", err
	}
	if err := plaintextWriter.Close(); err != nil {
		return "", err
	}
	if err := armorWriter.Close(); err != nil {
		return "", err
	}
	return buf.String(), nil
}

// PgpDecrypt decrypts an ASCII-armored PGP message with the recipient's
// private key and returns the plaintext. It is the twin of pgpDecrypt()
// in src/lib/pgp-encrypt.ts; an empty passphrase means "unprotected key".
func PgpDecrypt(armoredMessage, privateKeyArmored, passphrase string) (string, error) {
	if armoredMessage == "" {
		return "", errors.New("Armored message must not be empty.")
	}
	if privateKeyArmored == "" {
		return "", errors.New("Private key must not be empty.")
	}

	key, err := readEntity(strings.TrimSpace(privateKeyArmored))
	if err != nil {
		return "", err
	}
	if passphrase != "" {
		if err := unlockPrivateKey(key, passphrase); err != nil {
			return "", err
		}
	}

	block, err := armor.Decode(strings.NewReader(strings.TrimSpace(armoredMessage)))
	if err != nil {
		return "", err
	}
	md, err := openpgp.ReadMessage(block.Body, openpgp.EntityList{key}, nil, nil)
	if err != nil {
		return "", err
	}
	data, err := io.ReadAll(md.UnverifiedBody)
	if err != nil {
		return "", err
	}
	return string(data), nil
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →