gpg

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 19 Imported by: 3 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package gpg signs and verifies with OpenPGP.

Signing: a Signer produces cleartext (InRelease style) and detached signatures; LocalSigner implements it over a private key, with ASCII-armored (Release.gpg, repomd.xml.asc, .deb.asc) and binary (pacman .sig, RPM header signature) detached forms. GenerateEntity and ParsePrivateKey create and load keys.

Verifying: a Keyring holds public keys, armored or binary, and VerifyClearsigned and VerifyDetached check a signature against it. Failures map onto sentinels (ErrUnknownSigner, ErrBadSignature, ErrKeyExpired, ...), so a caller can tell "signed by someone we do not trust yet" from "the data was altered". Both refuse revoked and expired keys and expired signatures. For callers that check a signature themselves with the OpenPGP library (the RPM header signatures), Keyring.Entities lists the keys and CheckSigner applies the same revocation, expiry and key-flag rules to the key that made a signature.

What a caller trusts is policy and stays with the caller: which keyring applies to which repository, and whether an unsigned or unknown-signer repository is acceptable. The package never reads host paths on its own.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/M0Rf30/pkgformat/gpg"
)

func main() {
	entity, _ := gpg.GenerateEntity("Repo Signer", "", "repo@example.com", gpg.AlgorithmED25519)
	signer, _ := gpg.NewLocalSignerFromEntity(entity)

	release := "Suite: stable\nCodename: bookworm\n"

	// Sign: a detached signature, binary as a pacman .sig file holds it.
	sig, _ := signer.DetachedSignBinary(strings.NewReader(release))

	// Verify against the signer's public key.
	keyring, _ := signer.Keyring()

	v, err := gpg.VerifyDetached(keyring, strings.NewReader(release), sig)
	fmt.Println(v.Identity, err)

	_, err = gpg.VerifyDetached(keyring, strings.NewReader(release+"tampered"), sig)
	fmt.Println(err != nil)

}
Output:
Repo Signer <repo@example.com> <nil>
true

Index

Examples

Constants

View Source
const MaxKeyringBytes = 16 << 20

MaxKeyringBytes bounds the size of a keyring read from a reader or a file.

Variables

View Source
var (
	ErrUnsupportedAlgorithm = errors.New("unsupported key algorithm")
	ErrInvalidKey           = errors.New("not an ASCII-armored OpenPGP key")
	ErrNotPrivateKey        = errors.New("armored block does not contain a private key")
	ErrPassphraseRequired   = errors.New("private key is passphrase-protected")
	ErrBadPassphrase        = errors.New("wrong passphrase for private key")
	ErrKeyCannotSign        = errors.New("key cannot sign")
	ErrKeyRevoked           = errors.New("key is revoked")
	ErrKeyExpired           = errors.New("key is expired")
)

Sentinel errors for key parsing.

View Source
var (
	// ErrNoKeys is returned for a keyring that holds no usable public key.
	ErrNoKeys = errors.New("gpg: keyring holds no keys")
	// ErrKeyringTooLarge is returned for a keyring over MaxKeyringBytes.
	ErrKeyringTooLarge = errors.New("gpg: keyring too large")
	// ErrNotClearsigned is returned for input that is not a cleartext-signed
	// message.
	ErrNotClearsigned = errors.New("gpg: not a clear-signed message")
	// ErrUnsigned is returned for a cleartext message that carries no signature.
	ErrUnsigned = errors.New("gpg: message is not signed")
	// ErrUnknownSigner is returned when a well-formed signature was made by a
	// key that is not in the keyring. It differs from ErrBadSignature: the
	// signature may be genuine, the signer is merely not trusted yet.
	ErrUnknownSigner = errors.New("gpg: signature made by a key not in the keyring")
	// ErrBadSignature is returned when a signature is malformed or does not
	// match the data. It signals an attack or a broken mirror, never a missing
	// trust anchor.
	ErrBadSignature = errors.New("gpg: invalid signature")
	// ErrSignatureExpired is returned for a signature past its expiry.
	ErrSignatureExpired = errors.New("gpg: signature expired")
)

Sentinel errors of the verify side. Test with errors.Is; the cause reported by the OpenPGP library stays in the chain.

View Source
var (
	ErrNoKeysFound = errors.New("no keys found in keyring")
)

Sentinel errors for GPG operations.

View Source
var ErrPrivateKeyNotExportable = errors.New("gpg: private key is held by an external signer")

ErrPrivateKeyNotExportable is returned by the private key exports of a signer made by NewCryptoSigner: its key stays behind the crypto.Signer.

View Source
var ErrUnsupportedSigner = errors.New("gpg: crypto.Signer must hold an RSA or ECDSA key")

ErrUnsupportedSigner is returned by NewCryptoSigner for a crypto.Signer whose public key is neither RSA nor ECDSA.

Functions

func CheckSigner added in v0.3.1

func CheckSigner(entity *openpgp.Entity, key *packet.PublicKey, sig *packet.Signature, now time.Time) error

CheckSigner reports whether sig may be trusted to come from key, a key of entity (its primary key or one of its subkeys), at time now. It is the part of verification that does not depend on the signed data, for callers that hash the data themselves and call the cryptographic check of the OpenPGP library directly. VerifyDetached and VerifyClearsigned apply the same checks.

It fails with:

  • ErrKeyRevoked: the primary key, the subkey or the primary user id carries a revocation signature;
  • ErrKeyCannotSign: the key flags of the key do not allow signing, or the key has no valid self-signature or binding signature;
  • ErrKeyExpired: the primary key or the subkey is expired, or was created after now;
  • ErrSignatureExpired: sig, the binding signature of the subkey or its embedded back signature is past its expiry, or was made after now;
  • ErrBadSignature: sig or a self-signature has a critical notation that is not known;
  • ErrUnknownSigner: key is not a key of entity.

func GenerateEntity

func GenerateEntity(name, comment, email string, alg Algorithm) (*openpgp.Entity, error)

GenerateEntity generates a new key pair of the given type.

Types

type Algorithm

type Algorithm string

Algorithm names a key type GenerateEntity can generate.

const (
	// AlgorithmED25519 is an EdDSA key over Curve25519 (OpenPGP algorithm 22,
	// understood by GnuPG >= 2.1, apt's gpgv/sqv and dnf).
	AlgorithmED25519 Algorithm = "ed25519"
	// AlgorithmRSA4096 is a 4096-bit RSA key, the most widely compatible choice.
	AlgorithmRSA4096 Algorithm = "rsa4096"
	// AlgorithmRSA3072 is a 3072-bit RSA key, the GnuPG default size.
	AlgorithmRSA3072 Algorithm = "rsa3072"
	// AlgorithmP256 and AlgorithmP384 are ECDSA keys over NIST P-256 and P-384
	// (OpenPGP algorithm 19).
	AlgorithmP256 Algorithm = "p256"
	AlgorithmP384 Algorithm = "p384"
	// AlgorithmED25519V6 and AlgorithmED448V6 are version 6 keys (RFC 9580)
	// with the native Ed25519 and Ed448 algorithms (27 and 28), understood
	// by rpm 6 (Sequoia) and GnuPG-incompatible tools only.
	AlgorithmED25519V6 Algorithm = "ed25519-v6"
	AlgorithmED448V6   Algorithm = "ed448-v6"
)

func ParseAlgorithm

func ParseAlgorithm(s string) (Algorithm, error)

ParseAlgorithm validates an algorithm name; the empty string selects ed25519.

type KeyInfo

type KeyInfo struct {
	// Fingerprint is the upper-case hex fingerprint of the primary key.
	Fingerprint string
	// KeyID is the long (16 hex digit) key id.
	KeyID string
	// Algorithm is "ed25519", "rsa<bits>" or the OpenPGP algorithm name.
	Algorithm string
	// UserID is the primary user id ("Name (Comment) <email>"), if any.
	UserID string
	// ExpiresAt is nil for keys that never expire.
	ExpiresAt *time.Time
}

KeyInfo is the public description of a signing key.

type Keyring

type Keyring struct {
	// contains filtered or unexported fields
}

Keyring is a set of OpenPGP public keys a signature is checked against. The zero value and nil are empty keyrings.

func LoadKeyringDir

func LoadKeyringDir(dir string) (*Keyring, error)

LoadKeyringDir merges every *.gpg and *.asc file directly inside dir (not recursive, in name order). Entries that are unreadable or hold no key are skipped, as apt does for its trust directory; the result may therefore be empty (Len() == 0). An error is returned only when dir cannot be listed.

func LoadKeyringFile

func LoadKeyringFile(path string) (*Keyring, error)

LoadKeyringFile reads a keyring file, armored or binary.

func ParseKeyring

func ParseKeyring(data []byte) (*Keyring, error)

ParseKeyring reads public keys from data, ASCII-armored or binary (auto-detected). It fails with ErrNoKeys when data holds none and with ErrKeyringTooLarge above MaxKeyringBytes.

func ReadKeyring

func ReadKeyring(r io.Reader) (*Keyring, error)

ReadKeyring is ParseKeyring over a reader, reading at most MaxKeyringBytes.

func (*Keyring) Entities added in v0.3.1

func (k *Keyring) Entities() openpgp.EntityList

Entities returns the keys of the keyring as OpenPGP entities, for callers that check signatures themselves (see package rpm's Verify). The slice is a copy; the entities are shared. It is nil for an empty keyring.

func (*Keyring) Len

func (k *Keyring) Len() int

Len returns the number of primary keys in the keyring.

func (*Keyring) Merge

func (k *Keyring) Merge(other *Keyring)

Merge adds the keys of other to k. It is a no-op for a nil other.

type LocalSigner

type LocalSigner struct {
	// contains filtered or unexported fields
}

LocalSigner implements Signer using local GPG keys.

func NewCryptoSigner added in v0.4.0

func NewCryptoSigner(signer crypto.Signer, created time.Time, name, comment, email string) (*LocalSigner, error)

NewCryptoSigner returns a signer whose private key stays behind signer: a hardware security module, a cloud KMS, a smart card or an agent exposing the standard crypto.Signer interface. RSA and ECDSA (P-256, P-384, P-521) keys are supported; the private key is never read.

OpenPGP identifies a key by a fingerprint computed over its creation time, so created must be the same every time the same key is wrapped, or the fingerprint and key id change. The returned signer carries a self-signed user id built from name, comment and email (made with signer too), so LocalSigner.PublicKey exports a usable certificate.

The result implements every method of Signer and the SigningKey method that RPM signing needs; ExportPrivateKey and ExportUnprotectedPrivateKey fail with ErrPrivateKeyNotExportable.

func NewLocalSignerFromEntity

func NewLocalSignerFromEntity(entity *openpgp.Entity) (*LocalSigner, error)

NewLocalSignerFromEntity wraps an entity that carries a decrypted private key.

func NewLocalSignerFromFile

func NewLocalSignerFromFile(keyPath string, passphrase []byte) (*LocalSigner, error)

NewLocalSignerFromFile creates a signer from a key file.

func ParsePrivateKey

func ParsePrivateKey(armored io.Reader, passphrase []byte) (*LocalSigner, error)

ParsePrivateKey reads the first key of an armored private key block, unlocks it with passphrase when it is protected, and verifies that it can sign and is neither revoked nor expired.

func (*LocalSigner) CleartextSign

func (s *LocalSigner) CleartextSign(data io.Reader) (io.Reader, error)

CleartextSign implements Signer.CleartextSign.

func (*LocalSigner) DetachedSign

func (s *LocalSigner) DetachedSign(data io.Reader) ([]byte, error)

DetachedSign implements Signer.DetachedSign: an ASCII-armored detached signature, as published beside a Release or repomd.xml file.

func (*LocalSigner) DetachedSignBinary

func (s *LocalSigner) DetachedSignBinary(data io.Reader) ([]byte, error)

DetachedSignBinary produces a binary (not armored) detached signature, the form of a pacman .sig file and of an RPM header signature.

func (*LocalSigner) ExportPrivateKey

func (s *LocalSigner) ExportPrivateKey() ([]byte, error)

ExportPrivateKey exports the private key in armored format.

func (*LocalSigner) ExportUnprotectedPrivateKey

func (s *LocalSigner) ExportUnprotectedPrivateKey() ([]byte, error)

ExportUnprotectedPrivateKey serialises the private key without passphrase protection, as an armored block. The caller must seal the result before it is stored anywhere.

func (*LocalSigner) Info

func (s *LocalSigner) Info() KeyInfo

Info describes the key.

func (*LocalSigner) KeyFingerprint

func (s *LocalSigner) KeyFingerprint() string

KeyFingerprint implements Signer.KeyFingerprint.

func (*LocalSigner) KeyID

func (s *LocalSigner) KeyID() string

KeyID returns the short key ID (last 16 hex characters).

func (*LocalSigner) Keyring

func (s *LocalSigner) Keyring() (*Keyring, error)

Keyring returns the public part of the signer's key as a Keyring, ready to verify what the signer signed.

func (*LocalSigner) PublicKey

func (s *LocalSigner) PublicKey() ([]byte, error)

PublicKey implements Signer.PublicKey.

func (*LocalSigner) SigningKey

func (s *LocalSigner) SigningKey() (*packet.PrivateKey, error)

SigningKey returns the unlocked private key that makes signatures: the signing subkey when the entity has one, the primary key otherwise. It lets signers of other formats (RPM package signatures) use the same key.

type Signer

type Signer interface {
	// CleartextSign produces an InRelease-style cleartext signature
	CleartextSign(data io.Reader) (io.Reader, error)
	// DetachedSign produces a Release.gpg-style detached signature
	DetachedSign(data io.Reader) ([]byte, error)
	// PublicKey returns the ASCII-armored public key for client distribution
	PublicKey() ([]byte, error)
	// KeyFingerprint returns the key fingerprint
	KeyFingerprint() string
}

Signer defines the interface for GPG signing operations.

type Verified

type Verified struct {
	// Identity is the primary user id ("Name (Comment) <email>"), or the key id
	// when the key carries none.
	Identity string
	// KeyID is the long (16 hex digit) key id of the primary key.
	KeyID string
	// Fingerprint is the upper-case hex fingerprint of the primary key.
	Fingerprint string
}

Verified describes the key that produced a verified signature.

func VerifyClearsigned

func VerifyClearsigned(kr *Keyring, signed []byte) (body []byte, v Verified, err error)

VerifyClearsigned verifies an inline clear-signed message (an InRelease file) against kr and returns the unwrapped body. The body is LF-terminated: CRLF line endings are normalised and dash-escaping is undone. Data after the signature block is ignored.

func VerifyDetached

func VerifyDetached(kr *Keyring, data io.Reader, sig []byte) (Verified, error)

VerifyDetached verifies data against a detached signature. sig may be binary (a pacman .sig file, an RPM header signature) or ASCII-armored (Release.gpg, repomd.xml.asc, .deb.asc); the form is detected.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL