crypt

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Dec 30, 2025 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Overview

Package crypt provides PDF encryption and decryption. This file implements credential serialization for PDF security handlers.

Package crypt provides PDF encryption and decryption.

Package crypt provides PDF encryption and decryption. This file implements ISO 32004 ASN.1 type definitions for PDF MAC.

ISO 32004 defines the Message Authentication Code (MAC) mechanism for encrypted PDF documents to ensure document integrity.

Package crypt provides PDF encryption and decryption. This file implements PDF MAC (Message Authentication Code) as per ISO 32004.

Package crypt provides PDF encryption and decryption. This file implements public key encryption as per PDF specification.

Package crypt provides PDF encryption and decryption. This file implements RFC 4013 SASLprep for password preparation.

SASLprep is used in PDF 2.0 encryption (revision 6) for password normalization before hashing.

Package crypt provides encryption utility functions.

Index

Constants

View Source
const (
	OIDStringPdfMacIntegrityInfo = "1.0.32004.1.0"
	OIDStringPdfMacWrapKDF       = "1.0.32004.1.1"
	OIDStringPdfMacData          = "1.0.32004.1.2"
)

OID string representations for debugging and logging

View Source
const ISO32004AttributeType = "pdf_mac_data"

ISO32004AttributeType is the CMS attribute type for PDF MAC data.

View Source
const ISO32004ContentType = "pdf_mac_integrity_info"

ISO32004ContentType is the content type for PDF MAC integrity info.

View Source
const ISO32004KDFType = "pdf_mac_wrap_kdf"

ISO32004KDFType is the KDF algorithm identifier.

View Source
const ISO32004Version = 0

ISO32004Version is the current version of the ISO 32004 specification.

Variables

View Source
var (
	ErrCredentialNotRegistered   = errors.New("credential type not registered")
	ErrCredentialSerialization   = errors.New("credential serialization error")
	ErrCredentialDeserialization = errors.New("credential deserialization error")
)

Credential serialization errors

View Source
var (
	ErrInvalidPassword  = errors.New("invalid password")
	ErrUnsupportedCrypt = errors.New("unsupported encryption")
	ErrDecryptionFailed = errors.New("decryption failed")
)

Common errors

View Source
var (
	ErrPdfMacValidation     = errors.New("PDF MAC validation error")
	ErrPdfMacInvalidMAC     = errors.New("PDF MAC token has invalid MAC")
	ErrPdfMacMissingData    = errors.New("missing required PDF MAC data")
	ErrPdfMacInvalidDigest  = errors.New("document digest mismatch")
	ErrPdfMacUnsupportedAlg = errors.New("unsupported MAC algorithm")
)

PDF MAC related errors

View Source
var (
	// OID for PDF MAC integrity info content type: 1.0.32004.1.0
	OIDPdfMacIntegrityInfo = asn1.ObjectIdentifier{1, 0, 32004, 1, 0}
	// OID for PDF MAC wrap KDF: 1.0.32004.1.1
	OIDPdfMacWrapKDF = asn1.ObjectIdentifier{1, 0, 32004, 1, 1}
	// OID for PDF MAC data attribute: 1.0.32004.1.2
	OIDPdfMacData = asn1.ObjectIdentifier{1, 0, 32004, 1, 2}
	// OID for HMAC-SHA256
	OIDHmacSHA256 = asn1.ObjectIdentifier{1, 2, 840, 113549, 2, 9}
	// OID for AES-256 key wrap
	OIDAes256Wrap = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 45}
	// OID for AuthenticatedData content type
	OIDAuthenticatedData = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 16, 1, 2}
)

ISO32004 OIDs

View Source
var (
	OIDContentType            = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 3}
	OIDMessageDigest          = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 4}
	OIDCMSAlgorithmProtection = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 52}
)

Common CMS OIDs

View Source
var (
	OIDSHA3256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 8}
	OIDSHA3384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 9}
	OIDSHA3512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 10}
)

Digest algorithm OIDs (SHA256, SHA384, SHA512 defined in pubkey.go)

View Source
var (
	ErrNoCertificate           = errors.New("no certificate provided")
	ErrNoPrivateKey            = errors.New("no private key provided")
	ErrUnsupportedKeyType      = errors.New("unsupported key type")
	ErrRecipientNotFound       = errors.New("recipient not found in CMS")
	ErrInvalidEnvelopedData    = errors.New("invalid enveloped data")
	ErrInappropriateCredential = errors.New("inappropriate credential for operation")
	ErrKeyUsageViolation       = errors.New("certificate key usage does not permit key encipherment")
)

Public key encryption errors

View Source
var (
	OIDRSAESPKCSv15  = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
	OIDRSAESOAEP     = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 7}
	OIDAESWrap128    = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 5}
	OIDAESWrap192    = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 25}
	OIDAESWrap256    = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 45}
	OIDAESCBCPad128  = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 2}
	OIDAESCBCPad192  = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 22}
	OIDAESCBCPad256  = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 42}
	OIDSHA256        = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
	OIDSHA384        = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
	OIDSHA512        = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
	OIDEnvelopedData = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 3}
	OIDData          = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 1}
)

Common algorithm OIDs

View Source
var (
	OIDDHSinglePassStdDHSHA256KDF = asn1.ObjectIdentifier{1, 3, 132, 1, 11, 1}
	OIDDHSinglePassStdDHSHA384KDF = asn1.ObjectIdentifier{1, 3, 132, 1, 11, 2}
	OIDDHSinglePassStdDHSHA512KDF = asn1.ObjectIdentifier{1, 3, 132, 1, 11, 3}
)

ECDH key agreement OIDs (dhSinglePass-stdDH-*)

View Source
var (
	ErrSASLprepProhibited    = errors.New("SASLprep: prohibited character")
	ErrSASLprepBidirectional = errors.New("SASLprep: failed bidirectional check")
	ErrSASLprepEmpty         = errors.New("SASLprep: empty string")
)

SASLprep errors

View Source
var (
	ErrInvalidPadding   = errors.New("invalid PKCS7 padding")
	ErrInvalidBlockSize = errors.New("data not multiple of block size")
	ErrInvalidKeyLength = errors.New("invalid key length")
)
View Source
var AllowedMDAlgorithms = map[string]bool{
	"sha256":   true,
	"sha3_256": true,
	"sha384":   true,
	"sha3_384": true,
	"sha512":   true,
	"sha3_512": true,
	"shake256": true,
}

AllowedMDAlgorithms specifies permissible message digest algorithms for PDF MAC tokens.

View Source
var DefaultISO32004Registry = NewISO32004Registry()

DefaultISO32004Registry is the default registry instance.

Functions

func AESCBCDecrypt

func AESCBCDecrypt(key, data []byte) ([]byte, error)

AESCBCDecrypt decrypts AES-CBC encrypted data with PKCS7 padding. Expects IV to be prepended to ciphertext.

func AESCBCDecryptWithIV

func AESCBCDecryptWithIV(key, data, iv []byte, usePadding bool) ([]byte, error)

AESCBCDecryptWithIV decrypts AES-CBC encrypted data with explicit IV.

func AESCBCEncrypt

func AESCBCEncrypt(key, data, iv []byte) ([]byte, error)

AESCBCEncrypt encrypts data using AES-CBC with PKCS7 padding. If iv is nil, a random IV is generated. Returns the IV concatenated with the ciphertext.

func AddStandaloneMac

func AddStandaloneMac(
	fileEncryptionKey []byte,
	kdfSalt []byte,
	documentDigest []byte,
	mdAlgorithm string,
) ([]byte, error)

AddStandaloneMac creates a standalone MAC for a PDF. Returns the MAC token bytes.

func ComputeDocumentDigest

func ComputeDocumentDigest(reader io.ReaderAt, byteRanges [][2]int64, algorithm string) ([]byte, error)

ComputeDocumentDigest computes the document digest for MAC validation. byteRanges is a list of [offset, length] pairs.

func CreateEncryptDict

func CreateEncryptDict(handler *StandardSecurityHandler) map[string]interface{}

CreateEncryptDict creates an encryption dictionary.

func DeriveMacKEK

func DeriveMacKEK(fileEncryptionKey, kdfSalt []byte) ([]byte, error)

DeriveMacKEK derives the MAC key encryption key using HKDF. Uses HKDF-SHA256 with salt and info="PDFMAC".

func DeriveObjectKey

func DeriveObjectKey(fileKey []byte, objNum, genNum int, useAES bool) []byte

DeriveObjectKey derives the per-object encryption key. This is Algorithm 1 from PDF 1.7 specification.

func GetHashFunc

func GetHashFunc(algorithm string) (func() hash.Hash, error)

GetHashFunc returns a hash function constructor for the given algorithm name.

func GetISO32004OIDName

func GetISO32004OIDName(oid asn1.ObjectIdentifier) (string, bool)

GetISO32004OIDName returns the name for an ISO 32004 OID.

func GetRegisteredCredentialTypes

func GetRegisteredCredentialTypes() []string

GetRegisteredCredentialTypes returns a list of all registered credential type names.

func IsCredentialTypeRegistered

func IsCredentialTypeRegistered(name string) bool

IsCredentialTypeRegistered checks if a credential type is registered.

func IsISO32004OID

func IsISO32004OID(oid asn1.ObjectIdentifier) bool

IsISO32004OID checks if an OID is defined by ISO 32004.

func IsPdfMacDataAttribute

func IsPdfMacDataAttribute(attr *CMSAttribute) bool

IsPdfMacDataAttribute checks if a CMS attribute is a pdf_mac_data attribute.

func MarshalPdfMacIntegrityInfo

func MarshalPdfMacIntegrityInfo(info *PdfMacIntegrityInfo) ([]byte, error)

MarshalPdfMacIntegrityInfo marshals a PdfMacIntegrityInfo to ASN.1 DER.

func NewMD5

func NewMD5() hash.Hash

NewMD5 returns a new MD5 hash.

func NormalizePDFPassword

func NormalizePDFPassword(password string) (string, error)

NormalizePDFPassword normalizes a password for PDF 2.0 encryption. This is a convenience function that applies SASLprep with stored string rules.

func NormalizePDFPasswordBytes

func NormalizePDFPasswordBytes(password []byte) ([]byte, error)

NormalizePDFPasswordBytes normalizes a password from bytes for PDF 2.0 encryption.

func PKCS7Pad

func PKCS7Pad(data []byte, blockSize int) []byte

PKCS7Pad adds PKCS7 padding to data.

func PKCS7Unpad

func PKCS7Unpad(data []byte) ([]byte, error)

PKCS7Unpad removes PKCS7 padding from data.

func RC4Decrypt

func RC4Decrypt(key, data []byte) ([]byte, error)

RC4Decrypt decrypts data using RC4 (same as encrypt for RC4).

func RC4Encrypt

func RC4Encrypt(key, data []byte) ([]byte, error)

RC4Encrypt encrypts data using RC4.

func RegisterCredentialType

func RegisterCredentialType(name string, deserializer CredentialDeserializer)

RegisterCredentialType registers a credential type with its deserializer. This should be called during package initialization.

func SASLprep

func SASLprep(data string, prohibitUnassigned bool) (string, error)

SASLprep implements RFC 4013 SASLprep.

This function prepares a string for use in SASL authentication mechanisms. It performs the following steps:

  1. Map - Map certain characters to nothing or to space
  2. Normalize - Apply NFKC normalization
  3. Prohibit - Check for prohibited characters
  4. Check bidi - Check bidirectional string requirements

Parameters:

  • data: The string to SASLprep
  • prohibitUnassigned: If true, unassigned code points are prohibited (used for "stored strings"). If false, they are allowed (for "queries").

Returns the SASLprep'd string or an error.

func SASLprepQuery

func SASLprepQuery(data string) (string, error)

SASLprepQuery is a convenience function for queries. It calls SASLprep with prohibitUnassigned=false.

func SASLprepStored

func SASLprepStored(data string) (string, error)

SASLprepStored is a convenience function for stored strings. It calls SASLprep with prohibitUnassigned=true.

func TripleDESDecrypt

func TripleDESDecrypt(key, data, iv []byte) ([]byte, error)

TripleDESDecrypt decrypts data using Triple DES CBC.

func UnregisterCredentialType

func UnregisterCredentialType(name string)

UnregisterCredentialType removes a credential type from the registry. Primarily useful for testing.

func ValidatePdfMac

func ValidatePdfMac(
	tokenData []byte,
	fileEncryptionKey []byte,
	kdfSalt []byte,
	documentDigest []byte,
	signatureDigest []byte,
	mdAlgorithm string,
) error

ValidatePdfMac validates a PDF MAC in a document. This is a high-level validation function.

Types

type AlgorithmIdentifier

type AlgorithmIdentifier struct {
	Algorithm  asn1.ObjectIdentifier
	Parameters asn1.RawValue `asn1:"optional"`
}

AlgorithmIdentifier represents an algorithm with optional parameters.

type AuthStatus

type AuthStatus int

AuthStatus represents authentication status.

const (
	// AuthStatusFailed indicates authentication failed.
	AuthStatusFailed AuthStatus = iota
	// AuthStatusUser indicates user-level access.
	AuthStatusUser
	// AuthStatusOwner indicates owner-level access.
	AuthStatusOwner
)

type AuthenticatedData

type AuthenticatedData struct {
	Version          int
	RecipientInfos   []asn1.RawValue `asn1:"set"`
	MacAlgorithm     AlgorithmIdentifier
	DigestAlgorithm  AlgorithmIdentifier `asn1:"optional,explicit,tag:1"`
	EncapContentInfo EncapsulatedContentInfo
	AuthAttrs        asn1.RawValue `asn1:"optional,implicit,tag:2,set"`
	Mac              []byte
	UnauthAttrs      asn1.RawValue `asn1:"optional,implicit,tag:3,set"`
}

AuthenticatedData represents CMS AuthenticatedData.

type CMSAlgorithmProtection

type CMSAlgorithmProtection struct {
	DigestAlgorithm    AlgorithmIdentifier
	SignatureAlgorithm *AlgorithmIdentifier `asn1:"optional,implicit,tag:1"`
	MacAlgorithm       *AlgorithmIdentifier `asn1:"optional,implicit,tag:2"`
}

CMSAlgorithmProtection represents CMS algorithm protection attribute.

type CMSAttribute

type CMSAttribute struct {
	Type  asn1.ObjectIdentifier
	Value asn1.RawValue `asn1:"set"`
}

CMSAttribute represents a CMS attribute.

type ContentInfo

type ContentInfo struct {
	ContentType asn1.ObjectIdentifier
	Content     asn1.RawValue `asn1:"explicit,tag:0"`
}

ContentInfo represents CMS ContentInfo.

func ParsePdfMacDataAttribute

func ParsePdfMacDataAttribute(attr *CMSAttribute) ([]ContentInfo, error)

ParsePdfMacDataAttribute parses the value of a pdf_mac_data attribute.

type CredentialDeserializer

type CredentialDeserializer func(data []byte) (SerialisableCredential, error)

CredentialDeserializer is a function that deserializes credential data.

type CredentialStore

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

CredentialStore provides storage and retrieval of serialized credentials.

func NewCredentialStore

func NewCredentialStore() *CredentialStore

NewCredentialStore creates a new credential store.

func (*CredentialStore) Clear

func (s *CredentialStore) Clear()

Clear removes all credentials from the store.

func (*CredentialStore) Count

func (s *CredentialStore) Count() int

Count returns the number of credentials in the store.

func (*CredentialStore) Delete

func (s *CredentialStore) Delete(key string)

Delete removes a credential from the store.

func (*CredentialStore) Keys

func (s *CredentialStore) Keys() []string

Keys returns all keys in the store.

func (*CredentialStore) Load

Load retrieves a serialized credential by key.

func (*CredentialStore) LoadAndDeserialize

func (s *CredentialStore) LoadAndDeserialize(key string) (SerialisableCredential, error)

LoadAndDeserialize retrieves and deserializes a credential by key.

func (*CredentialStore) Store

func (s *CredentialStore) Store(key string, cred *SerialisedCredential)

Store stores a serialized credential with the given key.

func (*CredentialStore) StoreCredential

func (s *CredentialStore) StoreCredential(key string, cred SerialisableCredential) error

StoreCredential serializes and stores a credential.

type CryptFilter

type CryptFilter struct {
	// Type is the crypt filter type.
	Type CryptFilterType

	// KeyLength is the key length in bytes.
	KeyLength int

	// AuthEvent specifies when authentication occurs.
	AuthEvent string

	// Recipients for public key encryption.
	Recipients [][]byte
}

CryptFilter represents a PDF crypt filter.

func NewCryptFilter

func NewCryptFilter(filterType CryptFilterType, keyLength int) *CryptFilter

NewCryptFilter creates a new crypt filter.

func (*CryptFilter) Decrypt

func (f *CryptFilter) Decrypt(key, data []byte) ([]byte, error)

Decrypt decrypts data using the filter's algorithm.

func (*CryptFilter) Encrypt

func (f *CryptFilter) Encrypt(key, data []byte) ([]byte, error)

Encrypt encrypts data using the filter's algorithm.

type CryptFilterType

type CryptFilterType string

CryptFilterType represents the type of crypt filter.

const (
	CryptFilterNone     CryptFilterType = "None"
	CryptFilterV2       CryptFilterType = "V2"       // RC4
	CryptFilterAESV2    CryptFilterType = "AESV2"    // AES-128
	CryptFilterAESV3    CryptFilterType = "AESV3"    // AES-256
	CryptFilterIdentity CryptFilterType = "Identity" // No encryption
)

type EncapsulatedContentInfo

type EncapsulatedContentInfo struct {
	ContentType asn1.ObjectIdentifier
	Content     []byte `asn1:"optional,explicit,tag:0"`
}

EncapsulatedContentInfo represents encapsulated content.

type EncryptionRevision

type EncryptionRevision int

EncryptionRevision represents the encryption revision.

const (
	RevisionR2 EncryptionRevision = 2 // V2, 40-bit
	RevisionR3 EncryptionRevision = 3 // V2/V3, variable
	RevisionR4 EncryptionRevision = 4 // V4
	RevisionR5 EncryptionRevision = 5 // V5
	RevisionR6 EncryptionRevision = 6 // V5 with extension
)

type EncryptionVersion

type EncryptionVersion int

EncryptionVersion represents the PDF encryption version.

const (
	EncryptionV1 EncryptionVersion = 1 // 40-bit RC4
	EncryptionV2 EncryptionVersion = 2 // Variable-bit RC4
	EncryptionV3 EncryptionVersion = 3 // Unpublished
	EncryptionV4 EncryptionVersion = 4 // AES-128 or variable RC4
	EncryptionV5 EncryptionVersion = 5 // AES-256
)

type EnvelopeKeyDecrypter

type EnvelopeKeyDecrypter interface {
	// Certificate returns the recipient's certificate.
	Certificate() *x509.Certificate
	// Decrypt decrypts using key transport (RSA).
	Decrypt(encryptedKey []byte, algo KeyEncryptionAlgorithm) ([]byte, error)
	// DecryptWithExchange decrypts using key agreement (ECDH).
	DecryptWithExchange(encryptedKey []byte, algo KeyEncryptionAlgorithm,
		originatorKey []byte, ukm []byte) ([]byte, error)
}

EnvelopeKeyDecrypter decrypts envelope keys using recipient credentials.

type FileEncryptionKeyCredential

type FileEncryptionKeyCredential struct {
	Key []byte
}

FileEncryptionKeyCredential holds the raw file encryption key. This allows compatibility with any security handler.

func NewFileEncryptionKeyCredential

func NewFileEncryptionKeyCredential(key []byte) *FileEncryptionKeyCredential

NewFileEncryptionKeyCredential creates a new file encryption key credential.

func (*FileEncryptionKeyCredential) GetName

func (c *FileEncryptionKeyCredential) GetName() string

GetName returns the credential type name.

func (*FileEncryptionKeyCredential) SerialiseValue

func (c *FileEncryptionKeyCredential) SerialiseValue() ([]byte, error)

SerialiseValue serializes the file encryption key credential.

type ISO32004Registry

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

ISO32004Registry provides OID lookup for ISO 32004 types.

func NewISO32004Registry

func NewISO32004Registry() *ISO32004Registry

NewISO32004Registry creates a new ISO 32004 registry with default registrations.

func (*ISO32004Registry) LookupAttrType

func (r *ISO32004Registry) LookupAttrType(oid asn1.ObjectIdentifier) (string, bool)

LookupAttrType looks up an attribute type name by OID.

func (*ISO32004Registry) LookupContentType

func (r *ISO32004Registry) LookupContentType(oid asn1.ObjectIdentifier) (string, bool)

LookupContentType looks up a content type name by OID.

func (*ISO32004Registry) LookupKdfType

func (r *ISO32004Registry) LookupKdfType(oid asn1.ObjectIdentifier) (string, bool)

LookupKdfType looks up a KDF type name by OID.

type KdfAlgorithmId

type KdfAlgorithmId struct {
	Algorithm  asn1.ObjectIdentifier
	Parameters asn1.RawValue `asn1:"optional"`
}

KdfAlgorithmId represents a key derivation function algorithm identifier. This is used with the PDF MAC wrap KDF (OID 1.0.32004.1.1).

func NewPdfMacKdfAlgorithmId

func NewPdfMacKdfAlgorithmId() KdfAlgorithmId

NewPdfMacKdfAlgorithmId creates a new KDF algorithm identifier for PDF MAC.

func (*KdfAlgorithmId) IsPdfMacKdf

func (kdf *KdfAlgorithmId) IsPdfMacKdf() bool

IsPdfMacKdf checks if this is the PDF MAC KDF algorithm.

type KeyEncryptionAlgorithm

type KeyEncryptionAlgorithm struct {
	Algorithm  asn1.ObjectIdentifier
	Parameters interface{}
}

KeyEncryptionAlgorithm identifies the key encryption algorithm.

type MACLocation

type MACLocation string

MACLocation indicates where the MAC is stored in the PDF.

const (
	// MACLocationStandalone indicates MAC is in AuthCode dictionary.
	MACLocationStandalone MACLocation = "/Standalone"
	// MACLocationAttachedToSig indicates MAC is attached to a signature.
	MACLocationAttachedToSig MACLocation = "/AttachedToSig"
)

type PasswordCredential

type PasswordCredential struct {
	Password []byte
}

PasswordCredential is a simple credential containing a password.

func NewPasswordCredential

func NewPasswordCredential(password []byte) *PasswordCredential

NewPasswordCredential creates a new password credential.

func (*PasswordCredential) GetName

func (c *PasswordCredential) GetName() string

GetName returns the credential type name.

func (*PasswordCredential) SerialiseValue

func (c *PasswordCredential) SerialiseValue() ([]byte, error)

SerialiseValue serializes the password credential.

type PasswordRecipientInfo

type PasswordRecipientInfo struct {
	Version                int
	KeyDerivationAlgorithm AlgorithmIdentifier `asn1:"optional,implicit,tag:0"`
	KeyEncryptionAlgorithm AlgorithmIdentifier
	EncryptedKey           []byte
}

PasswordRecipientInfo represents CMS PasswordRecipientInfo.

type PdfMacDataAttribute

type PdfMacDataAttribute struct {
	Type   asn1.ObjectIdentifier
	Values SetOfContentInfo `asn1:"set"`
}

PdfMacDataAttribute represents the pdf_mac_data CMS attribute.

func NewPdfMacDataAttribute

func NewPdfMacDataAttribute(contentInfos ...ContentInfo) *PdfMacDataAttribute

NewPdfMacDataAttribute creates a new pdf_mac_data attribute.

type PdfMacIntegrityInfo

type PdfMacIntegrityInfo struct {
	Version         int
	DataDigest      []byte
	SignatureDigest []byte `asn1:"optional,tag:0"`
}

PdfMacIntegrityInfo represents the encapsulated content in a PDF MAC token. ASN.1 structure:

PdfMacIntegrityInfo ::= SEQUENCE {
    version         INTEGER,
    dataDigest      OCTET STRING,
    signatureDigest [0] IMPLICIT OCTET STRING OPTIONAL
}

func NewPdfMacIntegrityInfo

func NewPdfMacIntegrityInfo(dataDigest, signatureDigest []byte) *PdfMacIntegrityInfo

NewPdfMacIntegrityInfo creates a new PdfMacIntegrityInfo.

func ParsePdfMacIntegrityInfo

func ParsePdfMacIntegrityInfo(data []byte) (*PdfMacIntegrityInfo, error)

ParsePdfMacIntegrityInfo parses an ASN.1 encoded PdfMacIntegrityInfo.

func (*PdfMacIntegrityInfo) HasSignatureDigest

func (info *PdfMacIntegrityInfo) HasSignatureDigest() bool

HasSignatureDigest returns true if the integrity info includes a signature digest.

func (*PdfMacIntegrityInfo) Validate

func (info *PdfMacIntegrityInfo) Validate() error

Validate performs basic validation of the PdfMacIntegrityInfo.

type PdfMacTokenHandler

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

PdfMacTokenHandler creates and validates PDF MAC tokens.

func NewPdfMacTokenHandler

func NewPdfMacTokenHandler(macKEK []byte, mdAlgorithm string) *PdfMacTokenHandler

NewPdfMacTokenHandler creates a new PDF MAC token handler.

func NewPdfMacTokenHandlerFromKeyMaterial

func NewPdfMacTokenHandlerFromKeyMaterial(fileEncryptionKey, kdfSalt []byte, mdAlgorithm string) (*PdfMacTokenHandler, error)

NewPdfMacTokenHandlerFromKeyMaterial derives the handler from file encryption key and salt.

func (*PdfMacTokenHandler) BuildPdfMacToken

func (h *PdfMacTokenHandler) BuildPdfMacToken(documentDigest, signatureDigest []byte, dryRun bool) ([]byte, error)

BuildPdfMacToken builds a PDF MAC token (CMS AuthenticatedData).

func (*PdfMacTokenHandler) ComputeMAC

func (h *PdfMacTokenHandler) ComputeMAC(macKey, data []byte) []byte

ComputeMAC computes HMAC-SHA256 of the given data.

func (*PdfMacTokenHandler) DetermineTokenSize

func (h *PdfMacTokenHandler) DetermineTokenSize(includeSignatureDigest bool) (int, error)

DetermineTokenSize calculates the size of a PDF MAC token.

func (*PdfMacTokenHandler) GetHashFunc

func (h *PdfMacTokenHandler) GetHashFunc() (func() hash.Hash, error)

GetHashFunc returns the hash function for the configured algorithm.

func (*PdfMacTokenHandler) MDAlgorithm

func (h *PdfMacTokenHandler) MDAlgorithm() string

MDAlgorithm returns the message digest algorithm.

func (*PdfMacTokenHandler) ValidatePdfMacToken

func (h *PdfMacTokenHandler) ValidatePdfMacToken(tokenData, documentDigest, signatureDigest []byte) error

ValidatePdfMacToken validates a PDF MAC token.

type Permissions

type Permissions uint32

Permissions represents PDF permissions.

const (
	PermPrint            Permissions = 1 << 2
	PermModify           Permissions = 1 << 3
	PermCopy             Permissions = 1 << 4
	PermAnnotate         Permissions = 1 << 5
	PermFillForms        Permissions = 1 << 8
	PermAccessibility    Permissions = 1 << 9
	PermAssemble         Permissions = 1 << 10
	PermPrintHighQuality Permissions = 1 << 11
)

type PubKeyAdbeSubFilter

type PubKeyAdbeSubFilter string

PubKeyAdbeSubFilter represents the subfilter for public key encryption.

const (
	// SubFilterS3 is adbe.pkcs7.s3 - basic public key.
	SubFilterS3 PubKeyAdbeSubFilter = "/adbe.pkcs7.s3"
	// SubFilterS4 is adbe.pkcs7.s4 - without crypt filters.
	SubFilterS4 PubKeyAdbeSubFilter = "/adbe.pkcs7.s4"
	// SubFilterS5 is adbe.pkcs7.s5 - with crypt filters.
	SubFilterS5 PubKeyAdbeSubFilter = "/adbe.pkcs7.s5"
)

type PubKeyCryptFilter

type PubKeyCryptFilter struct {
	*CryptFilter
	Recipients      [][]byte // CMS EnvelopedData objects
	ActsAsDefault   bool
	EncryptMetadata bool
	// contains filtered or unexported fields
}

PubKeyCryptFilter is a crypt filter for public key encryption.

func NewPubKeyCryptFilter

func NewPubKeyCryptFilter(filterType CryptFilterType, keyLength int, actsAsDefault bool, encryptMetadata bool) *PubKeyCryptFilter

NewPubKeyCryptFilter creates a new public key crypt filter.

func (*PubKeyCryptFilter) AddRecipients

func (f *PubKeyCryptFilter) AddRecipients(certs []*x509.Certificate, policy RecipientEncryptionPolicy, perms PubKeyPermissions) error

AddRecipients adds recipients to the crypt filter.

func (*PubKeyCryptFilter) Authenticate

Authenticate authenticates using the provided credential.

func (*PubKeyCryptFilter) DeriveSharedKey

func (f *PubKeyCryptFilter) DeriveSharedKey(version SecurityHandlerVersion) ([]byte, error)

DeriveSharedKey derives the shared encryption key.

func (*PubKeyCryptFilter) SetSecurityHandler

func (f *PubKeyCryptFilter) SetSecurityHandler(handler *PubKeySecurityHandler)

SetSecurityHandler sets the security handler for this filter.

func (*PubKeyCryptFilter) SharedKey

func (f *PubKeyCryptFilter) SharedKey() []byte

SharedKey returns the shared encryption key.

type PubKeyPermissions

type PubKeyPermissions uint32

PubKeyPermissions represents permissions for public key encryption.

const (
	// PubKeyPermPrint allows printing.
	PubKeyPermPrint PubKeyPermissions = 1 << 2
	// PubKeyPermModify allows document modification.
	PubKeyPermModify PubKeyPermissions = 1 << 3
	// PubKeyPermCopy allows text/graphics extraction.
	PubKeyPermCopy PubKeyPermissions = 1 << 4
	// PubKeyPermAnnotate allows adding/modifying annotations.
	PubKeyPermAnnotate PubKeyPermissions = 1 << 5
	// PubKeyPermFillForms allows filling forms.
	PubKeyPermFillForms PubKeyPermissions = 1 << 8
	// PubKeyPermAccessibility allows accessibility extraction.
	PubKeyPermAccessibility PubKeyPermissions = 1 << 9
	// PubKeyPermAssemble allows document assembly.
	PubKeyPermAssemble PubKeyPermissions = 1 << 10
	// PubKeyPermPrintHighQuality allows high quality printing.
	PubKeyPermPrintHighQuality PubKeyPermissions = 1 << 11
	// PubKeyPermTolerateMissingMAC tolerates missing PDF MAC.
	PubKeyPermTolerateMissingMAC PubKeyPermissions = 1 << 12
)

func PubKeyPermissionsFromBytes

func PubKeyPermissionsFromBytes(data []byte) PubKeyPermissions

PubKeyPermissionsFromBytes creates permissions from a 4-byte array.

func (PubKeyPermissions) AllowEverything

func (p PubKeyPermissions) AllowEverything() PubKeyPermissions

AllowEverything returns permissions that allow everything.

func (PubKeyPermissions) AsBytes

func (p PubKeyPermissions) AsBytes() []byte

AsBytes returns the permissions as a 4-byte array (little-endian).

type PubKeySecurityHandler

type PubKeySecurityHandler struct {
	Version         SecurityHandlerVersion
	SubFilter       PubKeyAdbeSubFilter
	KeyLength       int
	EncryptMetadata bool
	KDFSalt         []byte
	// contains filtered or unexported fields
}

PubKeySecurityHandler handles public key encryption.

func BuildFromCerts

func BuildFromCerts(certs []*x509.Certificate, version SecurityHandlerVersion, perms PubKeyPermissions,
	policy RecipientEncryptionPolicy, encryptMetadata bool) (*PubKeySecurityHandler, error)

BuildFromCerts creates a security handler for the given certificates.

func NewPubKeySecurityHandler

func NewPubKeySecurityHandler(version SecurityHandlerVersion, subFilter PubKeyAdbeSubFilter, keyLength int) *PubKeySecurityHandler

NewPubKeySecurityHandler creates a new public key security handler.

func (*PubKeySecurityHandler) Authenticate

Authenticate authenticates using the provided credential.

func (*PubKeySecurityHandler) DecryptStream

func (h *PubKeySecurityHandler) DecryptStream(data []byte, objNum, genNum int) ([]byte, error)

DecryptStream decrypts a stream.

func (*PubKeySecurityHandler) DecryptString

func (h *PubKeySecurityHandler) DecryptString(data []byte, objNum, genNum int) ([]byte, error)

DecryptString decrypts a string.

func (*PubKeySecurityHandler) EncryptStream

func (h *PubKeySecurityHandler) EncryptStream(data []byte, objNum, genNum int) ([]byte, error)

EncryptStream encrypts a stream.

func (*PubKeySecurityHandler) EncryptString

func (h *PubKeySecurityHandler) EncryptString(data []byte, objNum, genNum int) ([]byte, error)

EncryptString encrypts a string.

func (*PubKeySecurityHandler) GetFileEncryptionKey

func (h *PubKeySecurityHandler) GetFileEncryptionKey() ([]byte, error)

GetFileEncryptionKey returns the file encryption key.

func (*PubKeySecurityHandler) GetName

func (h *PubKeySecurityHandler) GetName() string

GetName returns the security handler name.

type RecipientEncryptionPolicy

type RecipientEncryptionPolicy struct {
	// IgnoreKeyUsage ignores key usage bits in recipient certificate.
	IgnoreKeyUsage bool
	// PreferOAEP uses RSAES-OAEP for RSA recipients (not widely supported).
	PreferOAEP bool
}

RecipientEncryptionPolicy specifies encryption options for recipients.

type SecurityHandler

type SecurityHandler interface {
	// Authenticate authenticates with a password.
	Authenticate(password []byte) error
	// DecryptString decrypts a string.
	DecryptString(data []byte, objNum, genNum int) ([]byte, error)
	// DecryptStream decrypts a stream.
	DecryptStream(data []byte, objNum, genNum int) ([]byte, error)
	// EncryptString encrypts a string.
	EncryptString(data []byte, objNum, genNum int) ([]byte, error)
	// EncryptStream encrypts a stream.
	EncryptStream(data []byte, objNum, genNum int) ([]byte, error)
}

SecurityHandler handles PDF encryption/decryption.

type SecurityHandlerVersion

type SecurityHandlerVersion int

SecurityHandlerVersion represents the security handler version.

const (
	// SecurityHandlerVersionRC440 is RC4 40-bit (V1).
	SecurityHandlerVersionRC440 SecurityHandlerVersion = 1
	// SecurityHandlerVersionRC4Longer is RC4 longer keys (V2).
	SecurityHandlerVersionRC4Longer SecurityHandlerVersion = 2
	// SecurityHandlerVersionRC4OrAES128 is RC4 or AES-128 (V4).
	SecurityHandlerVersionRC4OrAES128 SecurityHandlerVersion = 4
	// SecurityHandlerVersionAES256 is AES-256 (V5).
	SecurityHandlerVersionAES256 SecurityHandlerVersion = 5
	// SecurityHandlerVersionAESGCM is AES-GCM (V6).
	SecurityHandlerVersionAESGCM SecurityHandlerVersion = 6
)

type SerialisableCredential

type SerialisableCredential interface {
	// GetName returns the type name of the credential.
	GetName() string

	// SerialiseValue serializes the credential to raw binary data.
	SerialiseValue() ([]byte, error)
}

SerialisableCredential is the interface for credentials that can be serialized.

func Deserialise

Deserialise deserializes a SerialisedCredential by looking up the proper deserializer and invoking it.

type SerialisedCredential

type SerialisedCredential struct {
	// CredentialType is the registered type name of the credential.
	CredentialType string

	// Data is the credential data as a byte string.
	Data []byte
}

SerialisedCredential represents a credential in serialized form.

func NewSerialisedCredential

func NewSerialisedCredential(credentialType string, data []byte) *SerialisedCredential

NewSerialisedCredential creates a new serialized credential.

func Serialise

Serialise serializes a SerialisableCredential to a SerialisedCredential.

type SetOfContentInfo

type SetOfContentInfo []ContentInfo

SetOfContentInfo represents a SET OF ContentInfo. Used for the pdf_mac_data attribute value.

type SimpleEnvelopeKeyDecrypter

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

SimpleEnvelopeKeyDecrypter implements EnvelopeKeyDecrypter with in-memory keys.

func NewSimpleEnvelopeKeyDecrypter

func NewSimpleEnvelopeKeyDecrypter(cert *x509.Certificate, privateKey interface{}) (*SimpleEnvelopeKeyDecrypter, error)

NewSimpleEnvelopeKeyDecrypter creates a new envelope key decrypter.

func (*SimpleEnvelopeKeyDecrypter) Certificate

func (d *SimpleEnvelopeKeyDecrypter) Certificate() *x509.Certificate

Certificate returns the recipient's certificate.

func (*SimpleEnvelopeKeyDecrypter) Decrypt

func (d *SimpleEnvelopeKeyDecrypter) Decrypt(encryptedKey []byte, algo KeyEncryptionAlgorithm) ([]byte, error)

Decrypt decrypts using RSA.

func (*SimpleEnvelopeKeyDecrypter) DecryptWithExchange

func (d *SimpleEnvelopeKeyDecrypter) DecryptWithExchange(encryptedKey []byte, algo KeyEncryptionAlgorithm,
	originatorKey []byte, ukm []byte) ([]byte, error)

DecryptWithExchange decrypts using ECDH key agreement.

type StandalonePdfMac

type StandalonePdfMac struct {
	ByteRange     []int
	MAC           []byte
	MACLocation   MACLocation
	BytesReserved int
}

StandalonePdfMac represents a standalone PDF MAC dictionary entry.

func NewStandalonePdfMac

func NewStandalonePdfMac(bytesReserved int) *StandalonePdfMac

NewStandalonePdfMac creates a new standalone PDF MAC.

type StandardSecurityHandler

type StandardSecurityHandler struct {
	Version     EncryptionVersion
	Revision    EncryptionRevision
	KeyLength   int
	Permissions Permissions
	OwnerKey    []byte // O value
	UserKey     []byte // U value
	OwnerE      []byte // OE value (R6)
	UserE       []byte // UE value (R6)
	Perms       []byte // Perms value (R6)
	FileID      []byte
	// contains filtered or unexported fields
}

StandardSecurityHandler implements the standard PDF security handler.

func NewStandardSecurityHandler

func NewStandardSecurityHandler(version EncryptionVersion, revision EncryptionRevision, keyLength int) *StandardSecurityHandler

NewStandardSecurityHandler creates a new standard security handler.

func (*StandardSecurityHandler) Authenticate

func (h *StandardSecurityHandler) Authenticate(password []byte) error

Authenticate implements SecurityHandler.

func (*StandardSecurityHandler) DecryptStream

func (h *StandardSecurityHandler) DecryptStream(data []byte, objNum, genNum int) ([]byte, error)

DecryptStream implements SecurityHandler.

func (*StandardSecurityHandler) DecryptString

func (h *StandardSecurityHandler) DecryptString(data []byte, objNum, genNum int) ([]byte, error)

DecryptString implements SecurityHandler.

func (*StandardSecurityHandler) EncryptStream

func (h *StandardSecurityHandler) EncryptStream(data []byte, objNum, genNum int) ([]byte, error)

EncryptStream implements SecurityHandler.

func (*StandardSecurityHandler) EncryptString

func (h *StandardSecurityHandler) EncryptString(data []byte, objNum, genNum int) ([]byte, error)

EncryptString implements SecurityHandler.

func (*StandardSecurityHandler) SetFileID

func (h *StandardSecurityHandler) SetFileID(id []byte)

SetFileID sets the file ID.

func (*StandardSecurityHandler) SetOwnerKey

func (h *StandardSecurityHandler) SetOwnerKey(o []byte)

SetOwnerKey sets the O value.

func (*StandardSecurityHandler) SetPermissions

func (h *StandardSecurityHandler) SetPermissions(p Permissions)

SetPermissions sets the permissions.

func (*StandardSecurityHandler) SetUseAES

func (h *StandardSecurityHandler) SetUseAES(useAES bool)

SetUseAES sets whether to use AES encryption.

func (*StandardSecurityHandler) SetUserKey

func (h *StandardSecurityHandler) SetUserKey(u []byte)

SetUserKey sets the U value.

Jump to

Keyboard shortcuts

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