go-jose.v2: gopkg.in/square/go-jose.v2 Index | Examples | Files | Directories

package jose

import "gopkg.in/square/go-jose.v2"

Package jose aims to provide an implementation of the Javascript Object Signing and Encryption set of standards. It implements encryption and signing based on the JSON Web Encryption and JSON Web Signature standards, with optional JSON Web Token support available in a sub-package. The library supports both the compact and full serialization formats, and has optional support for multiple recipients.

Code:

// Generate a public/private key pair to use for this example.
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
    panic(err)
}

// Instantiate an encrypter using RSA-OAEP with AES128-GCM. An error would
// indicate that the selected algorithm(s) are not currently supported.
publicKey := &privateKey.PublicKey
encrypter, err := NewEncrypter(A128GCM, Recipient{Algorithm: RSA_OAEP, Key: publicKey}, nil)
if err != nil {
    panic(err)
}

// Encrypt a sample plaintext. Calling the encrypter returns an encrypted
// JWE object, which can then be serialized for output afterwards. An error
// would indicate a problem in an underlying cryptographic primitive.
var plaintext = []byte("Lorem ipsum dolor sit amet")
object, err := encrypter.Encrypt(plaintext)
if err != nil {
    panic(err)
}

// Serialize the encrypted object using the full serialization format.
// Alternatively you can also use the compact format here by calling
// object.CompactSerialize() instead.
serialized := object.FullSerialize()

// Parse the serialized, encrypted JWE object. An error would indicate that
// the given input did not represent a valid message.
object, err = ParseEncrypted(serialized)
if err != nil {
    panic(err)
}

// Now we can decrypt and get back our original plaintext. An error here
// would indicate the the message failed to decrypt, e.g. because the auth
// tag was broken or the message was tampered with.
decrypted, err := object.Decrypt(privateKey)
if err != nil {
    panic(err)
}

fmt.Printf(string(decrypted))

Output:

Lorem ipsum dolor sit amet

Code:

// Generate a public/private key pair to use for this example.
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
    panic(err)
}

// Instantiate a signer using RSASSA-PSS (SHA512) with the given private key.
signer, err := NewSigner(SigningKey{Algorithm: PS512, Key: privateKey}, nil)
if err != nil {
    panic(err)
}

// Sign a sample payload. Calling the signer returns a protected JWS object,
// which can then be serialized for output afterwards. An error would
// indicate a problem in an underlying cryptographic primitive.
var payload = []byte("Lorem ipsum dolor sit amet")
object, err := signer.Sign(payload)
if err != nil {
    panic(err)
}

// Serialize the encrypted object using the full serialization format.
// Alternatively you can also use the compact format here by calling
// object.CompactSerialize() instead.
serialized := object.FullSerialize()

// Parse the serialized, protected JWS object. An error would indicate that
// the given input did not represent a valid message.
object, err = ParseSigned(serialized)
if err != nil {
    panic(err)
}

// Now we can verify the signature on the payload. An error here would
// indicate the the message failed to verify, e.g. because the signature was
// broken or the message was tampered with.
output, err := object.Verify(&privateKey.PublicKey)
if err != nil {
    panic(err)
}

fmt.Printf(string(output))

Output:

Lorem ipsum dolor sit amet

Index

Examples

Package Files

asymmetric.go crypter.go doc.go encoding.go jwe.go jwk.go jws.go shared.go signing.go symmetric.go

Constants

const (
    ED25519            = KeyAlgorithm("ED25519")
    RSA1_5             = KeyAlgorithm("RSA1_5")             // RSA-PKCS1v1.5
    RSA_OAEP           = KeyAlgorithm("RSA-OAEP")           // RSA-OAEP-SHA1
    RSA_OAEP_256       = KeyAlgorithm("RSA-OAEP-256")       // RSA-OAEP-SHA256
    A128KW             = KeyAlgorithm("A128KW")             // AES key wrap (128)
    A192KW             = KeyAlgorithm("A192KW")             // AES key wrap (192)
    A256KW             = KeyAlgorithm("A256KW")             // AES key wrap (256)
    DIRECT             = KeyAlgorithm("dir")                // Direct encryption
    ECDH_ES            = KeyAlgorithm("ECDH-ES")            // ECDH-ES
    ECDH_ES_A128KW     = KeyAlgorithm("ECDH-ES+A128KW")     // ECDH-ES + AES key wrap (128)
    ECDH_ES_A192KW     = KeyAlgorithm("ECDH-ES+A192KW")     // ECDH-ES + AES key wrap (192)
    ECDH_ES_A256KW     = KeyAlgorithm("ECDH-ES+A256KW")     // ECDH-ES + AES key wrap (256)
    A128GCMKW          = KeyAlgorithm("A128GCMKW")          // AES-GCM key wrap (128)
    A192GCMKW          = KeyAlgorithm("A192GCMKW")          // AES-GCM key wrap (192)
    A256GCMKW          = KeyAlgorithm("A256GCMKW")          // AES-GCM key wrap (256)
    PBES2_HS256_A128KW = KeyAlgorithm("PBES2-HS256+A128KW") // PBES2 + HMAC-SHA256 + AES key wrap (128)
    PBES2_HS384_A192KW = KeyAlgorithm("PBES2-HS384+A192KW") // PBES2 + HMAC-SHA384 + AES key wrap (192)
    PBES2_HS512_A256KW = KeyAlgorithm("PBES2-HS512+A256KW") // PBES2 + HMAC-SHA512 + AES key wrap (256)
)

Key management algorithms

const (
    EdDSA = SignatureAlgorithm("EdDSA")
    HS256 = SignatureAlgorithm("HS256") // HMAC using SHA-256
    HS384 = SignatureAlgorithm("HS384") // HMAC using SHA-384
    HS512 = SignatureAlgorithm("HS512") // HMAC using SHA-512
    RS256 = SignatureAlgorithm("RS256") // RSASSA-PKCS-v1.5 using SHA-256
    RS384 = SignatureAlgorithm("RS384") // RSASSA-PKCS-v1.5 using SHA-384
    RS512 = SignatureAlgorithm("RS512") // RSASSA-PKCS-v1.5 using SHA-512
    ES256 = SignatureAlgorithm("ES256") // ECDSA using P-256 and SHA-256
    ES384 = SignatureAlgorithm("ES384") // ECDSA using P-384 and SHA-384
    ES512 = SignatureAlgorithm("ES512") // ECDSA using P-521 and SHA-512
    PS256 = SignatureAlgorithm("PS256") // RSASSA-PSS using SHA256 and MGF1-SHA256
    PS384 = SignatureAlgorithm("PS384") // RSASSA-PSS using SHA384 and MGF1-SHA384
    PS512 = SignatureAlgorithm("PS512") // RSASSA-PSS using SHA512 and MGF1-SHA512
)

Signature algorithms

const (
    A128CBC_HS256 = ContentEncryption("A128CBC-HS256") // AES-CBC + HMAC-SHA256 (128)
    A192CBC_HS384 = ContentEncryption("A192CBC-HS384") // AES-CBC + HMAC-SHA384 (192)
    A256CBC_HS512 = ContentEncryption("A256CBC-HS512") // AES-CBC + HMAC-SHA512 (256)
    A128GCM       = ContentEncryption("A128GCM")       // AES-GCM (128)
    A192GCM       = ContentEncryption("A192GCM")       // AES-GCM (192)
    A256GCM       = ContentEncryption("A256GCM")       // AES-GCM (256)
)

Content encryption algorithms

const (
    NONE    = CompressionAlgorithm("")    // No compression
    DEFLATE = CompressionAlgorithm("DEF") // DEFLATE (RFC 1951)
)

Compression algorithms

Variables

var (
    // ErrCryptoFailure represents an error in cryptographic primitive. This
    // occurs when, for example, a message had an invalid authentication tag or
    // could not be decrypted.
    ErrCryptoFailure = errors.New("square/go-jose: error in cryptographic primitive")

    // ErrUnsupportedAlgorithm indicates that a selected algorithm is not
    // supported. This occurs when trying to instantiate an encrypter for an
    // algorithm that is not yet implemented.
    ErrUnsupportedAlgorithm = errors.New("square/go-jose: unknown/unsupported algorithm")

    // ErrUnsupportedKeyType indicates that the given key type/format is not
    // supported. This occurs when trying to instantiate an encrypter and passing
    // it a key of an unrecognized type or with unsupported parameters, such as
    // an RSA private key with more than two primes.
    ErrUnsupportedKeyType = errors.New("square/go-jose: unsupported key type/format")

    // ErrNotSupported serialization of object is not supported. This occurs when
    // trying to compact-serialize an object which can't be represented in
    // compact form.
    ErrNotSupported = errors.New("square/go-jose: compact serialization not supported for object")

    // ErrUnprotectedNonce indicates that while parsing a JWS or JWE object, a
    // nonce header parameter was included in an unprotected header object.
    ErrUnprotectedNonce = errors.New("square/go-jose: Nonce parameter included in unprotected header")
)

type CompressionAlgorithm Uses

type CompressionAlgorithm string

CompressionAlgorithm represents an algorithm used for plaintext compression.

type ContentEncryption Uses

type ContentEncryption string

ContentEncryption represents a content encryption algorithm.

type ContentType Uses

type ContentType string

ContentType represents type of the contained data.

type Encrypter Uses

type Encrypter interface {
    Encrypt(plaintext []byte) (*JSONWebEncryption, error)
    EncryptWithAuthData(plaintext []byte, aad []byte) (*JSONWebEncryption, error)
    Options() EncrypterOptions
}

Encrypter represents an encrypter which produces an encrypted JWE object.

Code:

// Encrypt a plaintext in order to get an encrypted JWE object.
var plaintext = []byte("This is a secret message")

encrypter.Encrypt(plaintext)

Code:

// Encrypt a plaintext in order to get an encrypted JWE object. Also attach
// some additional authenticated data (AAD) to the object. Note that objects
// with attached AAD can only be represented using full serialization.
var plaintext = []byte("This is a secret message")
var aad = []byte("This is authenticated, but public data")

encrypter.EncryptWithAuthData(plaintext, aad)

func NewEncrypter Uses

func NewEncrypter(enc ContentEncryption, rcpt Recipient, opts *EncrypterOptions) (Encrypter, error)

NewEncrypter creates an appropriate encrypter based on the key type

Code:

var publicKey *rsa.PublicKey

// Instantiate an encrypter using RSA-OAEP with AES128-GCM.
NewEncrypter(A128GCM, Recipient{Algorithm: RSA_OAEP, Key: publicKey}, nil)

// Instantiate an encrypter using RSA-PKCS1v1.5 with AES128-CBC+HMAC.
NewEncrypter(A128CBC_HS256, Recipient{Algorithm: RSA1_5, Key: publicKey}, nil)

Code:

var sharedKey []byte

// Instantiate an encrypter using AES128-GCM with AES-GCM key wrap.
NewEncrypter(A128GCM, Recipient{Algorithm: A128GCMKW, Key: sharedKey}, nil)

// Instantiate an encrypter using AES128-GCM directly, w/o key wrapping.
NewEncrypter(A128GCM, Recipient{Algorithm: DIRECT, Key: sharedKey}, nil)

func NewMultiEncrypter Uses

func NewMultiEncrypter(enc ContentEncryption, rcpts []Recipient, opts *EncrypterOptions) (Encrypter, error)

NewMultiEncrypter creates a multi-encrypter based on the given parameters

Code:

var publicKey *rsa.PublicKey
var sharedKey []byte

// Instantiate an encrypter using AES-GCM.
NewMultiEncrypter(A128GCM, []Recipient{
    {Algorithm: A128GCMKW, Key: sharedKey},
    {Algorithm: RSA_OAEP, Key: publicKey},
}, nil)

type EncrypterOptions Uses

type EncrypterOptions struct {
    Compression CompressionAlgorithm

    // Optional map of additional keys to be inserted into the protected header
    // of a JWS object. Some specifications which make use of JWS like to insert
    // additional values here. All values must be JSON-serializable.
    ExtraHeaders map[HeaderKey]interface{}
}

EncrypterOptions represents options that can be set on new encrypters.

func (*EncrypterOptions) WithContentType Uses

func (eo *EncrypterOptions) WithContentType(contentType ContentType) *EncrypterOptions

WithContentType adds a content type ("cty") header and returns the updated EncrypterOptions.

func (*EncrypterOptions) WithHeader Uses

func (eo *EncrypterOptions) WithHeader(k HeaderKey, v interface{}) *EncrypterOptions

WithHeader adds an arbitrary value to the ExtraHeaders map, initializing it if necessary. It returns itself and so can be used in a fluent style.

func (*EncrypterOptions) WithType Uses

func (eo *EncrypterOptions) WithType(typ ContentType) *EncrypterOptions

WithType adds a type ("typ") header and returns the updated EncrypterOptions.

type Header struct {
    KeyID      string
    JSONWebKey *JSONWebKey
    Algorithm  string
    Nonce      string

    // Any headers not recognised above get unmarshaled from JSON in a generic
    // manner and placed in this map.
    ExtraHeaders map[HeaderKey]interface{}
}

Header represents the read-only JOSE header for JWE/JWS objects.

type HeaderKey Uses

type HeaderKey string

A key in the protected header of a JWS object. Use of the Header... constants is preferred to enhance type safety.

const (
    HeaderType        HeaderKey = "typ" // string
    HeaderContentType           = "cty" // string

)

type JSONWebEncryption Uses

type JSONWebEncryption struct {
    Header Header
    // contains filtered or unexported fields
}

JSONWebEncryption represents an encrypted JWE object after parsing.

func ParseEncrypted Uses

func ParseEncrypted(input string) (*JSONWebEncryption, error)

ParseEncrypted parses an encrypted message in compact or full serialization format.

func (JSONWebEncryption) CompactSerialize Uses

func (obj JSONWebEncryption) CompactSerialize() (string, error)

CompactSerialize serializes an object using the compact serialization format.

func (JSONWebEncryption) Decrypt Uses

func (obj JSONWebEncryption) Decrypt(decryptionKey interface{}) ([]byte, error)

Decrypt and validate the object and return the plaintext. Note that this function does not support multi-recipient, if you desire multi-recipient decryption use DecryptMulti instead.

func (JSONWebEncryption) DecryptMulti Uses

func (obj JSONWebEncryption) DecryptMulti(decryptionKey interface{}) (int, Header, []byte, error)

DecryptMulti decrypts and validates the object and returns the plaintexts, with support for multiple recipients. It returns the index of the recipient for which the decryption was successful, the merged headers for that recipient, and the plaintext.

func (JSONWebEncryption) FullSerialize Uses

func (obj JSONWebEncryption) FullSerialize() string

FullSerialize serializes an object using the full JSON serialization format.

func (JSONWebEncryption) GetAuthData Uses

func (obj JSONWebEncryption) GetAuthData() []byte

GetAuthData retrieves the (optional) authenticated data attached to the object.

type JSONWebKey Uses

type JSONWebKey struct {
    Key          interface{}
    Certificates []*x509.Certificate
    KeyID        string
    Algorithm    string
    Use          string
}

JSONWebKey represents a public or private key in JWK format.

func (*JSONWebKey) IsPublic Uses

func (k *JSONWebKey) IsPublic() bool

IsPublic returns true if the JWK represents a public key (not symmetric, not private).

func (JSONWebKey) MarshalJSON Uses

func (k JSONWebKey) MarshalJSON() ([]byte, error)

MarshalJSON serializes the given key to its JSON representation.

func (*JSONWebKey) Thumbprint Uses

func (k *JSONWebKey) Thumbprint(hash crypto.Hash) ([]byte, error)

Thumbprint computes the JWK Thumbprint of a key using the indicated hash algorithm.

func (*JSONWebKey) UnmarshalJSON Uses

func (k *JSONWebKey) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON reads a key from its JSON representation.

func (*JSONWebKey) Valid Uses

func (k *JSONWebKey) Valid() bool

Valid checks that the key contains the expected parameters.

type JSONWebKeySet Uses

type JSONWebKeySet struct {
    Keys []JSONWebKey `json:"keys"`
}

JSONWebKeySet represents a JWK Set object.

func (*JSONWebKeySet) Key Uses

func (s *JSONWebKeySet) Key(kid string) []JSONWebKey

Key convenience method returns keys by key ID. Specification states that a JWK Set "SHOULD" use distinct key IDs, but allows for some cases where they are not distinct. Hence method returns a slice of JSONWebKeys.

type JSONWebSignature Uses

type JSONWebSignature struct {

    // Signatures attached to this object (may be more than one for multi-sig).
    // Be careful about accessing these directly, prefer to use Verify() or
    // VerifyMulti() to ensure that the data you're getting is verified.
    Signatures []Signature
    // contains filtered or unexported fields
}

JSONWebSignature represents a signed JWS object after parsing.

func ParseSigned Uses

func ParseSigned(input string) (*JSONWebSignature, error)

ParseSigned parses a signed message in compact or full serialization format.

func (JSONWebSignature) CompactSerialize Uses

func (obj JSONWebSignature) CompactSerialize() (string, error)

CompactSerialize serializes an object using the compact serialization format.

func (JSONWebSignature) FullSerialize Uses

func (obj JSONWebSignature) FullSerialize() string

FullSerialize serializes an object using the full JSON serialization format.

func (JSONWebSignature) Verify Uses

func (obj JSONWebSignature) Verify(verificationKey interface{}) ([]byte, error)

Verify validates the signature on the object and returns the payload. This function does not support multi-signature, if you desire multi-sig verification use VerifyMulti instead.

Be careful when verifying signatures based on embedded JWKs inside the payload header. You cannot assume that the key received in a payload is trusted.

func (JSONWebSignature) VerifyMulti Uses

func (obj JSONWebSignature) VerifyMulti(verificationKey interface{}) (int, Signature, []byte, error)

VerifyMulti validates (one of the multiple) signatures on the object and returns the index of the signature that was verified, along with the signature object and the payload. We return the signature and index to guarantee that callers are getting the verified value.

type KeyAlgorithm Uses

type KeyAlgorithm string

KeyAlgorithm represents a key management algorithm.

type NonceSource Uses

type NonceSource interface {
    Nonce() (string, error)
}

NonceSource represents a source of random nonces to go into JWS objects

type Recipient Uses

type Recipient struct {
    Algorithm KeyAlgorithm
    Key       interface{}
    KeyID     string
}

Recipient represents an algorithm/key to encrypt messages to.

type Signature Uses

type Signature struct {
    // Header fields, such as the signature algorithm
    Header Header

    // The actual signature value
    Signature []byte
    // contains filtered or unexported fields
}

Signature represents a single signature over the JWS payload and protected header.

type SignatureAlgorithm Uses

type SignatureAlgorithm string

SignatureAlgorithm represents a signature (or MAC) algorithm.

type Signer Uses

type Signer interface {
    Sign(payload []byte) (*JSONWebSignature, error)
    Options() SignerOptions
}

Signer represents a signer which takes a payload and produces a signed JWS object.

func NewMultiSigner Uses

func NewMultiSigner(sigs []SigningKey, opts *SignerOptions) (Signer, error)

NewMultiSigner creates a signer for multiple recipients

Code:

var privateKey *rsa.PrivateKey
var sharedKey []byte

// Instantiate a signer for multiple recipients.
NewMultiSigner([]SigningKey{
    {Algorithm: HS256, Key: sharedKey},
    {Algorithm: PS384, Key: privateKey},
}, nil)

func NewSigner Uses

func NewSigner(sig SigningKey, opts *SignerOptions) (Signer, error)

NewSigner creates an appropriate signer based on the key type

Code:

var rsaPrivateKey *rsa.PrivateKey
var ecdsaPrivateKey *ecdsa.PrivateKey

// Instantiate a signer using RSA-PKCS#1v1.5 with SHA-256.
NewSigner(SigningKey{Algorithm: RS256, Key: rsaPrivateKey}, nil)

// Instantiate a signer using ECDSA with SHA-384.
NewSigner(SigningKey{Algorithm: ES384, Key: ecdsaPrivateKey}, nil)

Code:

var sharedKey []byte

// Instantiate an signer using HMAC-SHA256.
NewSigner(SigningKey{Algorithm: HS256, Key: sharedKey}, nil)

// Instantiate an signer using HMAC-SHA512.
NewSigner(SigningKey{Algorithm: HS512, Key: sharedKey}, nil)

type SignerOptions Uses

type SignerOptions struct {
    NonceSource NonceSource
    EmbedJWK    bool

    // Optional map of additional keys to be inserted into the protected header
    // of a JWS object. Some specifications which make use of JWS like to insert
    // additional values here. All values must be JSON-serializable.
    ExtraHeaders map[HeaderKey]interface{}
}

SignerOptions represents options that can be set when creating signers.

func (*SignerOptions) WithContentType Uses

func (so *SignerOptions) WithContentType(contentType ContentType) *SignerOptions

WithContentType adds a content type ("cty") header and returns the updated SignerOptions.

func (*SignerOptions) WithHeader Uses

func (so *SignerOptions) WithHeader(k HeaderKey, v interface{}) *SignerOptions

WithHeader adds an arbitrary value to the ExtraHeaders map, initializing it if necessary. It returns itself and so can be used in a fluent style.

func (*SignerOptions) WithType Uses

func (so *SignerOptions) WithType(typ ContentType) *SignerOptions

WithType adds a type ("typ") header and returns the updated SignerOptions.

type SigningKey Uses

type SigningKey struct {
    Algorithm SignatureAlgorithm
    Key       interface{}
}

SigningKey represents an algorithm/key used to sign a message.

Directories

PathSynopsis
cipher
jose-util
jsonPackage json implements encoding and decoding of JSON objects as defined in RFC 4627.
jwtPackage jwt provides an implementation of the JSON Web Token standard.

Package jose imports 29 packages (graph) and is imported by 40 packages. Updated 2017-09-14. Refresh now. Tools for package owners.