jwe

package
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2021 License: MIT Imports: 26 Imported by: 6

Documentation

Overview

Package jwe implements JWE as described in https://tools.ietf.org/html/rfc7516

Index

Examples

Constants

View Source
const (
	TagSize = 16
)

Variables

View Source
var (
	ErrInvalidBlockSize         = errors.New("keywrap input must be 8 byte blocks")
	ErrInvalidCompactPartsCount = errors.New("compact JWE format must have five parts")
	ErrInvalidHeaderValue       = errors.New("invalid value for header key")
	ErrUnsupportedAlgorithm     = errors.New("unspported algorithm")
	ErrMissingPrivateKey        = errors.New("missing private key")
)

Errors used in JWE

View Source
var CbcAeadFetch = AeadFetchFunc(func(key []byte) (cipher.AEAD, error) {
	if debug.Enabled {
		debug.Printf("CbcAeadFetch: fetching key (%d)", len(key))
	}
	aead, err := aescbc.New(key, aes.NewCipher)
	if err != nil {
		if debug.Enabled {
			debug.Printf("CbcAeadFetch: failed to create aead fetcher %v (%d): %s", key, len(key), err)
		}
		return nil, errors.Wrap(err, "cipher: failed to create AES cipher for CBC")
	}
	return aead, nil
})
View Source
var GcmAeadFetch = AeadFetchFunc(func(key []byte) (cipher.AEAD, error) {
	aescipher, err := aes.NewCipher(key)
	if err != nil {
		if debug.Enabled {
			debug.Printf("GcmAeadFetch: failed to create cipher")
		}
		return nil, errors.Wrap(err, "cipher: failed to create AES cipher for GCM")
	}

	aead, err := cipher.NewGCM(aescipher)
	if err != nil {
		return nil, errors.Wrap(err, `failed to create GCM for cipher`)
	}
	return aead, nil
})

Functions

func Decrypt

func Decrypt(buf []byte, alg jwa.KeyEncryptionAlgorithm, key interface{}) ([]byte, error)

Decrypt takes the key encryption algorithm and the corresponding key to decrypt the JWE message, and returns the decrypted payload. The JWE message can be either compact or full JSON format.

func Encrypt

func Encrypt(payload []byte, keyalg jwa.KeyEncryptionAlgorithm, key interface{}, contentalg jwa.ContentEncryptionAlgorithm, compressalg jwa.CompressionAlgorithm) ([]byte, error)

Encrypt takes the plaintext payload and encrypts it in JWE compact format.

Example
privkey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
	log.Printf("failed to generate private key: %s", err)
	return
}

payload := []byte("Lorem Ipsum")

encrypted, err := Encrypt(payload, jwa.RSA1_5, &privkey.PublicKey, jwa.A128CBC_HS256, jwa.NoCompress)
if err != nil {
	log.Printf("failed to encrypt payload: %s", err)
	return
}

decrypted, err := Decrypt(encrypted, jwa.RSA1_5, privkey)
if err != nil {
	log.Printf("failed to decrypt: %s", err)
	return
}

if string(decrypted) != "Lorem Ipsum" {
	log.Printf("WHAT?!")
	return
}
Output:

func NewErrUnsupportedAlgorithm

func NewErrUnsupportedAlgorithm(alg, purpose string) errUnsupportedAlgorithm

NewErrUnsupportedAlgorithm creates a new UnsupportedAlgorithm error

Types

type AeadFetchFunc

type AeadFetchFunc func([]byte) (cipher.AEAD, error)

AeadFetchFunc fetches a AEAD cipher from the given key, and is represented by a function

func (AeadFetchFunc) AeadFetch

func (f AeadFetchFunc) AeadFetch(key []byte) (cipher.AEAD, error)

type AeadFetcher

type AeadFetcher interface {
	AeadFetch([]byte) (cipher.AEAD, error)
}

AeadFetcher is an interface for things that can fetch AEAD ciphers

type AesContentCipher

type AesContentCipher struct {
	AeadFetcher
	NonceGenerator KeyGenerator
	// contains filtered or unexported fields
}

AesContentCipher represents a cipher based on AES

func (AesContentCipher) KeySize

func (c AesContentCipher) KeySize() int

func (AesContentCipher) TagSize

func (c AesContentCipher) TagSize() int

type ByteKey

type ByteKey []byte

ByteKey is a generated key that only has the key's byte buffer as its instance data. If a ke needs to do more, such as providing values to be set in a JWE header, that key type wraps a ByteKey

func (ByteKey) Bytes

func (k ByteKey) Bytes() []byte

Bytes returns the byte from this ByteKey

type ByteSource

type ByteSource interface {
	Bytes() []byte
}

ByteSource is an interface for things that return a byte sequence. This is used for KeyGenerator so that the result of computations can carry more than just the generate byte sequence.

type ByteWithECPrivateKey

type ByteWithECPrivateKey struct {
	ByteKey
	PrivateKey *ecdsa.PrivateKey
}

ByteWithECPrivateKey holds the EC-DSA private key that generated the key along witht he key itself. This is required to set the proper values in the JWE headers

func (ByteWithECPrivateKey) HeaderPopulate

func (k ByteWithECPrivateKey) HeaderPopulate(h *Header)

HeaderPopulate populates the header with the required EC-DSA public key infromation ('epk' key)

type CompactSerialize

type CompactSerialize struct{}

CompactSerialize serializes the message into JWE compact serialized format

func (CompactSerialize) Serialize

func (s CompactSerialize) Serialize(m *Message) ([]byte, error)

Serialize converts the mssage into a JWE compact serialize format byte buffer

type ContentCipher

type ContentCipher interface {
	KeySize() int
	// contains filtered or unexported methods
}

ContentCipher knows how to encrypt/decrypt the content given a content encryption key and other data

type ContentEncrypter

type ContentEncrypter interface {
	Algorithm() jwa.ContentEncryptionAlgorithm
	Encrypt([]byte, []byte, []byte) ([]byte, []byte, []byte, error)
}

ContentEncrypter encrypts the content using the content using the encrypted key

type DirectDecrypt

type DirectDecrypt struct {
	Key []byte
}

DirectDecrypt does not encryption (Note: Unimplemented)

func (DirectDecrypt) Decrypt

func (d DirectDecrypt) Decrypt() ([]byte, error)

Decrypt for DirectDecrypt does not do anything other than return a copy of the embedded key

type EcdhesKeyGenerate

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

EcdhesKeyGenerate generates keys using ECDH-ES algorithm

func NewEcdhesKeyGenerate

func NewEcdhesKeyGenerate(alg jwa.KeyEncryptionAlgorithm, pubkey *ecdsa.PublicKey) (*EcdhesKeyGenerate, error)

NewEcdhesKeyGenerate creates a new key generator using ECDH-ES

func (EcdhesKeyGenerate) KeyGenerate

func (g EcdhesKeyGenerate) KeyGenerate() (ByteSource, error)

KeyGenerate generates new keys using ECDH-ES

func (EcdhesKeyGenerate) KeySize

func (g EcdhesKeyGenerate) KeySize() int

KeySize returns the key size associated with this generator

type EcdhesKeyWrapDecrypt

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

EcdhesKeyWrapDecrypt decrypts keys using ECDH-ES.

func NewEcdhesKeyWrapDecrypt

func NewEcdhesKeyWrapDecrypt(alg jwa.KeyEncryptionAlgorithm, pubkey *ecdsa.PublicKey, apu, apv []byte, privkey *ecdsa.PrivateKey) *EcdhesKeyWrapDecrypt

NewEcdhesKeyWrapDecrypt creates a new key decrypter using ECDH-ES

func (EcdhesKeyWrapDecrypt) Algorithm

Algorithm returns the key encryption algorithm being used

func (EcdhesKeyWrapDecrypt) KeyDecrypt

func (kw EcdhesKeyWrapDecrypt) KeyDecrypt(enckey []byte) ([]byte, error)

KeyDecrypt decrypts the encrypted key using ECDH-ES

type EcdhesKeyWrapEncrypt

type EcdhesKeyWrapEncrypt struct {
	KeyID string
	// contains filtered or unexported fields
}

EcdhesKeyWrapEncrypt encrypts content encryption keys using ECDH-ES.

func NewEcdhesKeyWrapEncrypt

func NewEcdhesKeyWrapEncrypt(alg jwa.KeyEncryptionAlgorithm, key *ecdsa.PublicKey) (*EcdhesKeyWrapEncrypt, error)

NewEcdhesKeyWrapEncrypt creates a new key encrypter based on ECDH-ES

func (EcdhesKeyWrapEncrypt) Algorithm

Algorithm returns the key encryption algorithm being used

func (EcdhesKeyWrapEncrypt) KeyEncrypt

func (kw EcdhesKeyWrapEncrypt) KeyEncrypt(cek []byte) (ByteSource, error)

KeyEncrypt encrypts the content encryption key using ECDH-ES

func (EcdhesKeyWrapEncrypt) Kid

func (kw EcdhesKeyWrapEncrypt) Kid() string

Kid returns the key ID associated with this encrypter

type EncodedHeader

type EncodedHeader struct {
	*Header
	// contains filtered or unexported fields
}

EncodedHeader represents a header value that is base64 encoded in JSON format

func NewEncodedHeader

func NewEncodedHeader() *EncodedHeader

NewEncodedHeader creates a new encoded Header object

func (EncodedHeader) Base64Encode

func (e EncodedHeader) Base64Encode() ([]byte, error)

Base64Encode creates the base64 encoded version of the JSON representation of this header

func (EncodedHeader) MarshalJSON

func (e EncodedHeader) MarshalJSON() ([]byte, error)

MarshalJSON generates the JSON representation of this header

func (*EncodedHeader) UnmarshalJSON

func (e *EncodedHeader) UnmarshalJSON(buf []byte) error

UnmarshalJSON parses the JSON buffer into a Header

type Encrypter

type Encrypter interface {
	Encrypt([]byte) (*Message, error)
}

Encrypter is the top level structure that encrypts the given payload to a JWE message

type EssentialHeader

type EssentialHeader struct {
	AgreementPartyUInfo    buffer.Buffer                  `json:"apu,omitempty"`
	AgreementPartyVInfo    buffer.Buffer                  `json:"apv,omitempty"`
	Algorithm              jwa.KeyEncryptionAlgorithm     `json:"alg,omitempty"`
	ContentEncryption      jwa.ContentEncryptionAlgorithm `json:"enc,omitempty"`
	ContentType            string                         `json:"cty,omitempty"`
	Compression            jwa.CompressionAlgorithm       `json:"zip,omitempty"`
	Critical               []string                       `json:"crit,omitempty"`
	EphemeralPublicKey     *jwk.ECDSAPublicKey            `json:"epk,omitempty"`
	Jwk                    jwk.Key                        `json:"jwk,omitempty"` // public key
	JwkSetURL              *url.URL                       `json:"jku,omitempty"`
	KeyID                  string                         `json:"kid,omitempty"`
	Type                   string                         `json:"typ,omitempty"` // e.g. "JWT"
	X509Url                *url.URL                       `json:"x5u,omitempty"`
	X509CertChain          []string                       `json:"x5c,omitempty"`
	X509CertThumbprint     string                         `json:"x5t,omitempty"`
	X509CertThumbprintS256 string                         `json:"x5t#S256,omitempty"`
}

EssentialHeader is a set of headers that are already defined in RFC 7516`

func (*EssentialHeader) Copy

func (h *EssentialHeader) Copy(h2 *EssentialHeader)

Copy copies the other heder over this one

func (*EssentialHeader) Merge

func (h *EssentialHeader) Merge(h2 *EssentialHeader)

Merge merges the current header with another.

type GenericContentCrypt

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

GenericContentCrypt encrypts a message by applying all the necessary modifications to the keys and the contents

func (GenericContentCrypt) Algorithm

func (GenericContentCrypt) Decrypt

func (c GenericContentCrypt) Decrypt(cek, iv, ciphertext, tag, aad []byte) ([]byte, error)

func (GenericContentCrypt) Encrypt

func (c GenericContentCrypt) Encrypt(cek, plaintext, aad []byte) ([]byte, []byte, []byte, error)

func (GenericContentCrypt) KeySize

func (c GenericContentCrypt) KeySize() int
type Header struct {
	*EssentialHeader `json:"-"`
	PrivateParams    map[string]interface{} `json:"-"`
}

Header represents a jws header.

func NewHeader

func NewHeader() *Header

NewHeader creates a new Header object

func (*Header) Copy

func (h *Header) Copy(h2 *Header) error

Copy copies the other heder over this one

func (*Header) Get

func (h *Header) Get(key string) (interface{}, error)

Get returns the header key

func (Header) MarshalJSON

func (h Header) MarshalJSON() ([]byte, error)

MarshalJSON generates the JSON representation of this header

func (*Header) Merge

func (h *Header) Merge(h2 *Header) (*Header, error)

Merge merges the current header with another.

func (*Header) Set

func (h *Header) Set(key string, value interface{}) error

Set sets the value of the given key to the given value. If it's one of the known keys, it will be set in EssentialHeader field. Otherwise, it is set in PrivateParams field.

func (*Header) UnmarshalJSON

func (h *Header) UnmarshalJSON(data []byte) error

UnmarshalJSON parses the JSON buffer into a Header

type HeaderPopulater

type HeaderPopulater interface {
	HeaderPopulate(*Header)
}

HeaderPopulater is an interface for things that may modify the JWE header. e.g. ByteWithECPrivateKey

type JSONSerialize

type JSONSerialize struct {
	Pretty bool
}

JSONSerialize serializes the message into JWE JSON serialized format. If you set `Pretty` to true, `json.MarshalIndent` is used instead of `json.Marshal`

func (JSONSerialize) Serialize

func (s JSONSerialize) Serialize(m *Message) ([]byte, error)

Serialize converts the mssage into a JWE JSON serialize format byte buffer

type KeyDecrypter

type KeyDecrypter interface {
	Algorithm() jwa.KeyEncryptionAlgorithm
	KeyDecrypt([]byte) ([]byte, error)
}

KeyDecrypter is an interface for things that can decrypt keys

func BuildKeyDecrypter

func BuildKeyDecrypter(alg jwa.KeyEncryptionAlgorithm, h *Header, key interface{}, keysize int) (KeyDecrypter, error)

BuildKeyDecrypter creates a new KeyDecrypter instance from the given parameters. It is used by the Message.Decrypt method to create key decrypter(s) from the given message. `keysize` is only used by some decrypters. Pass the value from ContentCipher.KeySize().

type KeyEncrypter

type KeyEncrypter interface {
	Algorithm() jwa.KeyEncryptionAlgorithm
	KeyEncrypt([]byte) (ByteSource, error)
	// Kid returns the key id for this KeyEncrypter. This exists so that
	// you can pass in a KeyEncrypter to MultiEncrypt, you can rest assured
	// that the generated key will have the proper key ID.
	Kid() string
}

KeyEncrypter is an interface for things that can encrypt keys

type KeyGenerator

type KeyGenerator interface {
	KeySize() int
	KeyGenerate() (ByteSource, error)
}

KeyGenerator generates the raw content encryption keys

type KeyWrapEncrypt

type KeyWrapEncrypt struct {
	KeyID string
	// contains filtered or unexported fields
}

KeyWrapEncrypt encrypts content encryption keys using AES-CGM key wrap. Contrary to what the name implies, it also decrypt encrypted keys

func NewKeyWrapEncrypt

func NewKeyWrapEncrypt(alg jwa.KeyEncryptionAlgorithm, sharedkey []byte) (KeyWrapEncrypt, error)

NewKeyWrapEncrypt creates a key-wrap encryptor using AES-CGM. Although the name suggests otherwise, this does the decryption as well.

func (KeyWrapEncrypt) Algorithm

func (kw KeyWrapEncrypt) Algorithm() jwa.KeyEncryptionAlgorithm

Algorithm returns the key encryption algorithm being used

func (KeyWrapEncrypt) KeyDecrypt

func (kw KeyWrapEncrypt) KeyDecrypt(enckey []byte) ([]byte, error)

KeyDecrypt decrypts the encrypted key using AES-CGM key unwrap

func (KeyWrapEncrypt) KeyEncrypt

func (kw KeyWrapEncrypt) KeyEncrypt(cek []byte) (ByteSource, error)

KeyEncrypt encrypts the given content encryption key

func (KeyWrapEncrypt) Kid

func (kw KeyWrapEncrypt) Kid() string

Kid returns the key ID associated with this encrypter

type Message

type Message struct {
	AuthenticatedData    buffer.Buffer  `json:"aad,omitempty"`
	CipherText           buffer.Buffer  `json:"ciphertext"`
	InitializationVector buffer.Buffer  `json:"iv,omitempty"`
	ProtectedHeader      *EncodedHeader `json:"protected"`
	Recipients           []Recipient    `json:"recipients"`
	Tag                  buffer.Buffer  `json:"tag,omitempty"`
	UnprotectedHeader    *Header        `json:"unprotected,omitempty"`
}

Message contains the entire encrypted JWE message

func NewMessage

func NewMessage() *Message

NewMessage creates a new message

func Parse

func Parse(buf []byte) (*Message, error)

Parse parses the JWE message into a Message object. The JWE message can be either compact or full JSON format.

func ParseString

func ParseString(s string) (*Message, error)

ParseString is the same as Parse, but takes a string.

func (*Message) Decrypt

func (m *Message) Decrypt(alg jwa.KeyEncryptionAlgorithm, key interface{}) ([]byte, error)

Decrypt decrypts the message using the specified algorithm and key

type MultiEncrypt

type MultiEncrypt struct {
	ContentEncrypter ContentEncrypter
	KeyGenerator     KeyGenerator // KeyGenerator creates the random CEK.
	KeyEncrypters    []KeyEncrypter
}

MultiEncrypt is the default Encrypter implementation.

func NewMultiEncrypt

func NewMultiEncrypt(cc ContentEncrypter, kg KeyGenerator, ke ...KeyEncrypter) *MultiEncrypt

NewMultiEncrypt creates a new Encrypt struct. The caller is responsible for instantiating valid inputs for ContentEncrypter, KeyGenerator, and KeyEncrypters.

func (MultiEncrypt) Encrypt

func (e MultiEncrypt) Encrypt(plaintext []byte) (*Message, error)

Encrypt takes the plaintext and encrypts into a JWE message.

type RSAOAEPKeyDecrypt

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

RSAOAEPKeyDecrypt decrypts keys using RSA OAEP algorithm

func NewRSAOAEPKeyDecrypt

func NewRSAOAEPKeyDecrypt(alg jwa.KeyEncryptionAlgorithm, privkey *rsa.PrivateKey) (*RSAOAEPKeyDecrypt, error)

NewRSAOAEPKeyDecrypt creates a new key decrypter using RSA OAEP

func (RSAOAEPKeyDecrypt) Algorithm

Algorithm returns the key encryption algorithm being used

func (RSAOAEPKeyDecrypt) KeyDecrypt

func (d RSAOAEPKeyDecrypt) KeyDecrypt(enckey []byte) ([]byte, error)

KeyDecrypt decryptes the encrypted key using RSA OAEP

type RSAOAEPKeyEncrypt

type RSAOAEPKeyEncrypt struct {
	KeyID string
	// contains filtered or unexported fields
}

RSAOAEPKeyEncrypt encrypts keys using RSA OAEP algorithm

func NewRSAOAEPKeyEncrypt

func NewRSAOAEPKeyEncrypt(alg jwa.KeyEncryptionAlgorithm, pubkey *rsa.PublicKey) (*RSAOAEPKeyEncrypt, error)

NewRSAOAEPKeyEncrypt creates a new key encrypter using RSA OAEP

func (RSAOAEPKeyEncrypt) Algorithm

Algorithm returns the key encryption algorithm being used

func (RSAOAEPKeyEncrypt) KeyEncrypt

func (e RSAOAEPKeyEncrypt) KeyEncrypt(cek []byte) (ByteSource, error)

KeyEncrypt encrypts the content encryption key using RSA OAEP

func (RSAOAEPKeyEncrypt) Kid

func (e RSAOAEPKeyEncrypt) Kid() string

Kid returns the key ID associated with this encrypter

type RSAPKCS15KeyDecrypt

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

RSAPKCS15KeyDecrypt decrypts keys using RSA PKCS1v15 algorithm

func NewRSAPKCS15KeyDecrypt

func NewRSAPKCS15KeyDecrypt(alg jwa.KeyEncryptionAlgorithm, privkey *rsa.PrivateKey, keysize int) *RSAPKCS15KeyDecrypt

NewRSAPKCS15KeyDecrypt creates a new decrypter using RSA PKCS1v15

func (RSAPKCS15KeyDecrypt) Algorithm

Algorithm returns the key encryption algorithm being used

func (RSAPKCS15KeyDecrypt) KeyDecrypt

func (d RSAPKCS15KeyDecrypt) KeyDecrypt(enckey []byte) ([]byte, error)

KeyDecrypt decryptes the encrypted key using RSA PKCS1v1.5

type RSAPKCSKeyEncrypt

type RSAPKCSKeyEncrypt struct {
	KeyID string
	// contains filtered or unexported fields
}

RSAPKCSKeyEncrypt encrypts keys using RSA PKCS1v15 algorithm

func NewRSAPKCSKeyEncrypt

func NewRSAPKCSKeyEncrypt(alg jwa.KeyEncryptionAlgorithm, pubkey *rsa.PublicKey) (*RSAPKCSKeyEncrypt, error)

NewRSAPKCSKeyEncrypt creates a new key encrypter using PKCS1v15

func (RSAPKCSKeyEncrypt) Algorithm

Algorithm returns the key encryption algorithm being used

func (RSAPKCSKeyEncrypt) KeyEncrypt

func (e RSAPKCSKeyEncrypt) KeyEncrypt(cek []byte) (ByteSource, error)

KeyEncrypt encrypts the content encryption key using RSA PKCS1v15

func (RSAPKCSKeyEncrypt) Kid

func (e RSAPKCSKeyEncrypt) Kid() string

Kid returns the key ID associated with this encrypter

type RandomKeyGenerate

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

RandomKeyGenerate generates random keys

func NewRandomKeyGenerate

func NewRandomKeyGenerate(n int) RandomKeyGenerate

NewRandomKeyGenerate creates a new KeyGenerator that returns randome bytes

func (RandomKeyGenerate) KeyGenerate

func (g RandomKeyGenerate) KeyGenerate() (ByteSource, error)

KeyGenerate generates a random new key

func (RandomKeyGenerate) KeySize

func (g RandomKeyGenerate) KeySize() int

KeySize returns the key size

type Recipient

type Recipient struct {
	Header       *Header       `json:"header"`
	EncryptedKey buffer.Buffer `json:"encrypted_key"`
}

Recipient holds the encrypted key and hints to decrypt the key

func NewRecipient

func NewRecipient() *Recipient

NewRecipient creates a Recipient object

type RsaContentCipher

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

RsaContentCipher represents a cipher based on RSA

func NewRsaContentCipher

func NewRsaContentCipher(alg jwa.ContentEncryptionAlgorithm, pubkey *rsa.PublicKey) (*RsaContentCipher, error)

type Serializer

type Serializer interface {
	Serialize(*Message) ([]byte, error)
}

Serializer converts an encrypted message into a byte buffer

type StaticKeyGenerate

type StaticKeyGenerate []byte

StaticKeyGenerate uses a static byte buffer to provide keys.

func (StaticKeyGenerate) KeyGenerate

func (g StaticKeyGenerate) KeyGenerate() (ByteSource, error)

KeyGenerate returns the key

func (StaticKeyGenerate) KeySize

func (g StaticKeyGenerate) KeySize() int

KeySize returns the size of the key

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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