### Run jose-util Tests with Cram Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1.1/jose-util This example demonstrates how to build the `jose-util` command and then execute its tests using the `cram` testing framework. `cram` can be installed via `pip` or `apt`. ```Shell go build && PATH=$PWD:$PATH cram -v jose-util.t ``` -------------------------------- ### Install jose-util CLI Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/jose-util@v4.1 Installs the `jose-util` command-line utility using `go install`. This command fetches the latest version of the tool from its GitHub repository and compiles it, making it available in your Go binary path. ```Shell go install github.com/go-jose/go-jose/v4/jose-util@latest ``` -------------------------------- ### Install jose-util Go Command-Line Utility Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/jose-util This command installs the `jose-util` command-line utility from the `go-jose` repository using Go's module-aware installation. It fetches the latest version of the utility, making it available in your Go binary path. ```Shell go install github.com/go-jose/go-jose/v4/jose-util@latest ``` -------------------------------- ### Go NewSigner Example with Public Key Algorithms Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1 Demonstrates creating a `NewSigner` using public key algorithms. Examples include RS256 with an RSA private key and ES384 with an ECDSA private key. ```Go 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) ``` -------------------------------- ### Install jose-util CLI Tool Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1.1/jose-util This command installs the `jose-util` command-line utility using the Go module system. It fetches the latest version of the utility from its GitHub repository and makes it available in your Go binary path. ```Shell $ go install github.com/go-jose/go-jose/v4/jose-util@latest ``` -------------------------------- ### Go NewSigner Example with Symmetric Key Algorithms Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1 Shows how to create a `NewSigner` using symmetric key algorithms. Examples include HMAC-SHA256 and HMAC-SHA512 with a shared key. ```Go 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) ``` -------------------------------- ### Go-jose NewMultiEncrypter Example Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/index Provides an example of using `NewMultiEncrypter` to encrypt data for both a symmetric shared key recipient and an RSA public key recipient simultaneously. It shows how to combine different recipient types. ```go 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) ``` -------------------------------- ### Go NewMultiSigner Example Usage Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1 Illustrates how to instantiate a `NewMultiSigner` with multiple `SigningKey` instances, demonstrating the use of different algorithms like HS256 and PS384 for various recipients. ```Go var privateKey *rsa.PrivateKey var sharedKey []byte // Instantiate a signer for multiple recipients. NewMultiSigner([]SigningKey{ {Algorithm: HS256, Key: sharedKey}, {Algorithm: PS384, Key: privateKey}, }, nil) ``` -------------------------------- ### Go: Example of Signing a JWT Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1.1/jwt This example illustrates how to create and serialize a signed JWT. It sets up a "jose.Signer" with an HMAC key, populates standard JWT claims including subject, issuer, notBefore, and audience, and then uses the "jwt.Signed" builder to generate the token. ```Go key := []byte("0102030405060708090A0B0C0D0E0F10") sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: key}, (&jose.SignerOptions{}).WithType("JWT")) if err != nil { fmt.Printf("making signer: %s\n", err) return } cl := jwt.Claims{ Subject: "subject", Issuer: "issuer", NotBefore: jwt.NewNumericDate(time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC)), Audience: jwt.Audience{"leela", "fry"}, } raw, err := jwt.Signed(sig).Claims(cl).Serialize() if err != nil { fmt.Printf("signing JWT: %s\n", err) return } fmt.Println(raw) ``` -------------------------------- ### Go: Example of Encrypting a JWT Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1.1/jwt This example demonstrates the process of creating and serializing an encrypted JWT. It involves initializing a "jose.Encrypter" with a symmetric key, defining standard JWT claims, and then using the "jwt.Encrypted" builder to generate the token. ```Go enc, err := jose.NewEncrypter( jose.A128GCM, jose.Recipient{Algorithm: jose.DIRECT, Key: sharedEncryptionKey}, (&jose.EncrypterOptions{}).WithType("JWT"), ) if err != nil { fmt.Printf("making encrypter: %s\n", err) return } cl := jwt.Claims{ Subject: "subject", Issuer: "issuer", } raw, err := jwt.Encrypted(enc).Claims(cl).Serialize() if err != nil { fmt.Printf("encrypting JWT: %s\n", err) return } fmt.Println(raw) ``` -------------------------------- ### Go: Example of Encrypting a JWT Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/jwt Demonstrates how to create and serialize an encrypted JWT using `go-jose`. It initializes an encrypter with AES-128 GCM and direct key agreement, then builds a JWT with standard claims. The example prints the raw encrypted token. ```Go enc, err := jose.NewEncrypter( jose.A128GCM, jose.Recipient{Algorithm: jose.DIRECT, Key: sharedEncryptionKey}, (&jose.EncrypterOptions{}).WithType("JWT"), ) if err != nil { fmt.Printf("making encrypter: %s\n", err) return } cl := jwt.Claims{ Subject: "subject", Issuer: "issuer", } raw, err := jwt.Encrypted(enc).Claims(cl).Serialize() if err != nil { fmt.Printf("encrypting JWT: %s\n", err) return } fmt.Println(raw) ``` -------------------------------- ### Go: Example of Signing a JWT Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/jwt Illustrates how to create and serialize a signed JWT using `go-jose`. It sets up an HS256 signer, defines standard JWT claims including subject, issuer, not-before time, and audience. The example prints the raw signed token. ```Go key := []byte("0102030405060708090A0B0C0D0E0F10") sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: key}, (&jose.SignerOptions{}).WithType("JWT")) if err != nil { fmt.Printf("making signer: %s\n", err) return } cl := jwt.Claims{ Subject: "subject", Issuer: "issuer", NotBefore: jwt.NewNumericDate(time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC)), Audience: jwt.Audience{"leela", "fry"}, } raw, err := jwt.Signed(sig).Claims(cl).Serialize() if err != nil { fmt.Printf("signing JWT: %s\n", err) return } fmt.Println(raw) ``` -------------------------------- ### Example: Validate JWT Claims (Go) Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/jwt This Go example demonstrates how to use `jwt.Claims.Validate` to verify a manually constructed JWT claim set. It initializes a `jwt.Claims` object with various fields and then validates it against specific expected issuer and time values. The program prints 'valid!' if the validation succeeds, showcasing a basic usage scenario. ```Go package main import ( "fmt" "time" "github.com/go-jose/go-jose/v4/jwt" ) func main() { cl := jwt.Claims{ Subject: "subject", Issuer: "issuer", NotBefore: jwt.NewNumericDate(time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC)), Expiry: jwt.NewNumericDate(time.Date(2016, 1, 1, 0, 15, 0, 0, time.UTC)), Audience: jwt.Audience{"leela", "fry"}, } err := cl.Validate(jwt.Expected{ Issuer: "issuer", Time: time.Date(2016, 1, 1, 0, 10, 0, 0, time.UTC), }) if err != nil { fmt.Printf("validating claims: %s\n", err) return } fmt.Printf("valid!") } ``` -------------------------------- ### Go JWT: JSONWebToken.Claims Example (Map) Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/jwt Shows how to deserialize JWT claims into a `map[string]interface{}` using the `Claims` method. This example parses a signed JWT and then extracts the issuer and subject into a generic map. ```Go raw := `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOiJzdWJqZWN0In0.OFD0iVfPczqWBA_TRi1jGB5PF699eekcHt4D6qNoimc` tok, err := jwt.ParseSigned(raw, []jose.SignatureAlgorithm{jose.HS256}) if err != nil { fmt.Printf("parsing JWT: %s\n", err) return } out := make(map[string]interface{}) if err := tok.Claims(sharedKey, &out); err != nil { fmt.Printf("validating claims: %s\n", err) return } fmt.Printf("iss: %s, sub: %s\n", out["iss"], out["sub"]) ``` -------------------------------- ### Go: Instantiate Signer with Public Key Algorithms Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/index Illustrates creating a signer for public key algorithms like RSA-PKCS#1v1.5 and ECDSA using `NewSigner`. It provides examples for both RS256 with an RSA private key and ES384 with an ECDSA private key. ```Go 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) ``` -------------------------------- ### Go: Instantiate Multi-Recipient Signer Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/index Demonstrates how to create a signer for multiple recipients using `NewMultiSigner`. This example shows how to specify different algorithms and keys, such as HS256 and PS384, for each recipient. ```Go var privateKey *rsa.PrivateKey var sharedKey []byte // Instantiate a signer for multiple recipients. NewMultiSigner([]SigningKey{ {Algorithm: HS256, Key: sharedKey}, {Algorithm: PS384, Key: privateKey}, }, nil) ``` -------------------------------- ### Go-jose Encrypter.Encrypt Method Usage Example Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/index Demonstrates how to use the `Encrypt` method of the `Encrypter` interface to encrypt a plaintext byte slice into a JWE object. ```Go // Encrypt a plaintext in order to get an encrypted JWE object. var plaintext = []byte("This is a secret message") encrypter.Encrypt(plaintext) ``` -------------------------------- ### Go: Instantiate Signer with Symmetric Key Algorithms Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/index Shows how to create a signer for symmetric key algorithms such as HMAC-SHA256 and HMAC-SHA512 using `NewSigner`. The examples demonstrate using a shared key for different HMAC variants. ```Go 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) ``` -------------------------------- ### Go-jose NewEncrypter Example with RSA Public Key Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/index Illustrates how to use `NewEncrypter` with an RSA public key. It shows instantiation for RSA-OAEP with AES128-GCM and RSA-PKCS1v1.5 with AES128-CBC+HMAC, demonstrating different encryption and key management algorithms. ```go 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) ``` -------------------------------- ### Go: Example of Signing a JWT with Multiple Claims Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1.1/jwt This example demonstrates how to add multiple sets of claims to a single signed JWT. It shows combining a standard "jwt.Claims" struct with a custom anonymous struct containing additional fields like "Scopes", before serializing the token. Note: The "signer" variable is assumed to be initialized from a previous context. ```Go c := &jwt.Claims{ Subject: "subject", Issuer: "issuer", } c2 := struct { Scopes []string }{ []string{"foo", "bar"}, } raw, err := jwt.Signed(signer).Claims(c).Claims(c2).Serialize() if err != nil { fmt.Printf("validating claims: %s\n", err) return } fmt.Println(raw) ``` -------------------------------- ### Go-jose Encrypter.Encrypt Method Usage Example Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1 Illustrates how to use the `Encrypt` method of the `Encrypter` interface to encrypt a plaintext byte slice and obtain an encrypted JSON Web Encryption (JWE) object. ```go // Encrypt a plaintext in order to get an encrypted JWE object. var plaintext = []byte("This is a secret message") encrypter.Encrypt(plaintext) ``` -------------------------------- ### Go-jose NewEncrypter Example with Symmetric Key Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/index Demonstrates `NewEncrypter` usage with a symmetric shared key. Examples include AES128-GCM with AES-GCM key wrap and direct AES128-GCM encryption without key wrapping, showcasing symmetric key handling. ```go 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) ``` -------------------------------- ### Go: Example of Adding Multiple Claims to a Signed JWT Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/jwt Shows how to add multiple sets of claims to a JWT using the `Signed` builder. It combines standard JWT claims with custom claims (e.g., `Scopes`) before serialization. This demonstrates flexible claim management, assuming `signer` is already initialized. ```Go c := &jwt.Claims{ Subject: "subject", Issuer: "issuer", } c2 := struct { Scopes []string }{ []string{"foo", "bar"}, } raw, err := jwt.Signed(signer).Claims(c).Claims(c2).Serialize() if err != nil { fmt.Printf("validating claims: %s\n", err) return } fmt.Println(raw) ``` -------------------------------- ### Go Struct Field JSON Tag Examples Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/json Examples demonstrating various ways to use JSON struct tags in Go to control how struct fields are marshaled into JSON, including ignoring fields, renaming keys, and omitting empty values. ```Go // Field is ignored by this package. Field int `json:"-"` // Field appears in JSON as key "myName". Field int `json:"myName"` // Field appears in JSON as key "myName" and // the field is omitted from the object if its value is empty, // as defined above. Field int `json:"myName,omitempty"` // Field appears in JSON as key "Field" (the default), but // the field is skipped if empty. // Note the leading comma. Field int `json:",omitempty"` ``` -------------------------------- ### Go JWT: ParseEncrypted Example Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/jwt Demonstrates parsing an encrypted JWT (JWE) using `jwt.ParseEncrypted` with `jose.DIRECT` key algorithm and `jose.A128GCM` content encryption. After successful parsing, it extracts and prints the issuer and subject claims using the `Claims` method. ```Go key := []byte("itsa16bytesecret") raw := `eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0..jg45D9nmr6-8awml.z-zglLlEw9MVkYHi-Znd9bSwc-oRGbqKzf9WjXqZxno.kqji2DiZHZmh-1bLF6ARPw` tok, err := jwt.ParseEncrypted(raw, []jose.KeyAlgorithm{jose.DIRECT}, []jose.ContentEncryption{jose.A128GCM}) if err != nil { fmt.Printf("parsing JWT: %s\n", err) return } out := jwt.Claims{} if err := tok.Claims(key, &out); err != nil { fmt.Printf("validating claims: %s\n", err) return } fmt.Printf("iss: %s, sub: %s\n", out.Issuer, out.Subject) ``` -------------------------------- ### Go: Example of Signing a JWT with Private Claims Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1.1/jwt This example illustrates how to include custom, private claims within a signed JWT. It emphasizes the use of "json" struct tags (e.g., `json:"custom"`) on the private claim struct fields to ensure correct serialization into the JWT payload, mirroring "encoding/json" behavior. ```Go key := []byte("0102030405060708090A0B0C0D0E0F10") sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: key}, (&jose.SignerOptions{}).WithType("JWT")) if err != nil { fmt.Printf("making signer: %s\n", err) return } cl := jwt.Claims{ Subject: "subject", Issuer: "issuer", NotBefore: jwt.NewNumericDate(time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC)), Audience: jwt.Audience{"leela", "fry"}, } // When setting private claims, make sure to add struct tags // to specify how to serialize the field. The naming behavior // should match the encoding/json package otherwise. privateCl := struct { CustomClaim string `json:"custom"` }{ "custom claim value", } raw, err := jwt.Signed(sig).Claims(cl).Claims(privateCl).Serialize() if err != nil { fmt.Printf("signing JWT: %s\n", err) return } fmt.Println(raw) ``` -------------------------------- ### Extract JWT Claims to Map Example (Go) Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1.1/jwt Demonstrates extracting JWT claims into a `map[string]interface{}` using `tok.Claims` after parsing a signed JWT. Expected output: iss: issuer, sub: subject ```Go raw := `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOiJzdWJqZWN0In0.OFD0iVfPczqWBA_TRi1jGB5PF699eekcHt4D6qNoimc` tok, err := jwt.ParseSigned(raw, []jose.SignatureAlgorithm{jose.HS256}) if err != nil { fmt.Printf("parsing JWT: %s\n", err) return } out := make(map[string]interface{}) if err := tok.Claims(sharedKey, &out); err != nil { fmt.Printf("validating claims: %s\n", err) return } fmt.Printf("iss: %s, sub: %s\n", out["iss"], out["sub"]) ``` -------------------------------- ### Parse Encrypted JWT Example (Go) Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1.1/jwt Demonstrates parsing an encrypted JWT (JWE) using `jwt.ParseEncrypted` with a direct key and A128GCM content encryption. It then decrypts and validates claims using `tok.Claims`. Expected output: iss: issuer, sub: subject ```Go key := []byte("itsa16bytesecret") raw := `eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0..jg45D9nmr6-8awml.z-zglLlEw9MVkYHi-Znd9bSwc-oRGbqKzf9WjXqZxno.kqji2DiZHZmh-1bLF6ARPw` tok, err := jwt.ParseEncrypted(raw, []jose.KeyAlgorithm{jose.DIRECT}, []jose.ContentEncryption{jose.A128GCM}) if err != nil { fmt.Printf("parsing JWT: %s\n", err) return } out := jwt.Claims{} if err := tok.Claims(key, &out); err != nil { fmt.Printf("validating claims: %s\n", err) return } fmt.Printf("iss: %s, sub: %s\n", out.Issuer, out.Subject) ``` -------------------------------- ### Go JOSE: Sign and Verify JWS Object Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1 This Go example illustrates the complete process of JSON Web Signature (JWS) using the `go-jose` library. It involves generating RSA keys, signing a payload with RSASSA-PSS (SHA512), serializing the JWS object, and then parsing and verifying its signature. The code demonstrates how to ensure data integrity and authenticity. ```Go // 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 signed object using the JWS JSON 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, []SignatureAlgorithm{PS512}) if err != nil { panic(err) } // Now we can verify the signature on the payload. An error here would // indicate that 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.Print(string(output)) ``` -------------------------------- ### Example: Validate Parsed JWT Claims (Go) Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/jwt This example illustrates the validation of JWT claims after parsing a raw JWT string. It first parses a JWT using `jwt.ParseSigned`, then extracts the claims into a `jwt.Claims` struct. Finally, it validates these extracted claims against expected issuer and subject values, demonstrating a common real-world use case for token validation. ```Go raw := `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOiJzdWJqZWN0In0.OFD0iVfPczqWBA_TRi1jGB5PF699eekcHt4D6qNoimc` tok, err := jwt.ParseSigned(raw, []jose.SignatureAlgorithm{jose.HS256}) if err != nil { fmt.Printf("parsing JWT: %s\n", err) return } cl := jwt.Claims{} if err := tok.Claims(sharedKey, &cl); err != nil { fmt.Printf("validating claims: %s\n", err) return } err = cl.Validate(jwt.Expected{ Issuer: "issuer", Subject: "subject", }) if err != nil { fmt.Printf("validating claims: %s\n", err) return } fmt.Printf("valid!") ``` -------------------------------- ### Go Struct Field JSON Tagging Examples Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1.1/json Illustrates common JSON struct tag patterns in Go for controlling marshaling behavior, such as ignoring fields, custom naming, and conditional omission of empty fields. ```Go // Field is ignored by this package. Field int `json:"-"` // Field appears in JSON as key "myName". Field int `json:"myName"` // Field appears in JSON as key "myName" and // the field is omitted from the object if its value is empty, // as defined above. Field int `json:"myName,omitempty"` // Field appears in JSON as key "Field" (the default), but // the field is skipped if empty. // Note the leading comma. Field int `json:",omitempty"` ``` -------------------------------- ### Go-jose Encrypter.EncryptWithAuthData Method Usage Example Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1 Demonstrates the usage of the `EncryptWithAuthData` method from the `Encrypter` interface. This method encrypts plaintext and attaches additional authenticated data (AAD), which requires JWE JSON Serialization. ```go // 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 JWE JSON Serialization. var plaintext = []byte("This is a secret message") var aad = []byte("This is authenticated, but public data") encrypter.EncryptWithAuthData(plaintext, aad) ``` -------------------------------- ### Generate Encryption Keys with jose-util (ECDH-ES) Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1.1/jose-util Generates cryptographic keys using the jose-util command-line tool. This example specifically creates a key for encryption (--use enc) using the ECDH-ES+A128KW algorithm, suitable for JSON Web Encryption (JWE). ```Shell jose-util generate-key --use enc --alg ECDH-ES+A128KW ``` -------------------------------- ### Parse Signed JWT Example (Go) Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1.1/jwt Illustrates parsing a signed JWT (JWS) using `jwt.ParseSigned` with HS256 signature algorithm. It then validates and extracts claims using `tok.Claims`. Expected output: iss: issuer, sub: subject ```Go raw := `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOiJzdWJqZWN0In0.OFD0iVfPczqWBA_TRi1jGB5PF699eekcHt4D6qNoimc` tok, err := jwt.ParseSigned(raw, []jose.SignatureAlgorithm{jose.HS256}) if err != nil { fmt.Printf("parsing JWT: %s\n", err) return } out := jwt.Claims{} if err := tok.Claims(sharedKey, &out); err != nil { fmt.Printf("validating claims: %s\n", err) return } fmt.Printf("iss: %s, sub: %s\n", out.Issuer, out.Subject) ``` -------------------------------- ### Go JWT: ParseSigned Example Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/jwt Illustrates parsing a signed JWT (JWS) using `jwt.ParseSigned` with the `jose.HS256` signature algorithm. Following successful parsing, it validates and extracts the issuer and subject claims from the token. ```Go raw := `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOiJzdWJqZWN0In0.OFD0iVfPczqWBA_TRi1jGB5PF699eekcHt4D6qNoimc` tok, err := jwt.ParseSigned(raw, []jose.SignatureAlgorithm{jose.HS256}) if err != nil { fmt.Printf("parsing JWT: %s\n", err) return } out := jwt.Claims{} if err := tok.Claims(sharedKey, &out); err != nil { fmt.Printf("validating claims: %s\n", err) return } fmt.Printf("iss: %s, sub: %s\n", out.Issuer, out.Subject) ``` -------------------------------- ### Go-jose Encrypter.EncryptWithAuthData Method Usage Example Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/index Illustrates the usage of the `EncryptWithAuthData` method to encrypt plaintext and attach additional authenticated data (AAD) to the JWE object, noting that AAD requires JWE JSON Serialization. ```Go // 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 JWE JSON Serialization. var plaintext = []byte("This is a secret message") var aad = []byte("This is authenticated, but public data") encrypter.EncryptWithAuthData(plaintext, aad) ``` -------------------------------- ### Go JOSE: Encrypt and Decrypt JWE Object Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1 This Go example demonstrates end-to-end JSON Web Encryption (JWE) using the `go-jose` library. It covers generating RSA keys, encrypting a plaintext with RSA-OAEP and AES128-GCM, serializing the JWE object, and subsequently parsing and decrypting it. The process showcases both encryption and decryption flows for secure data exchange. ```Go // 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 JWE JSON 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, []KeyAlgorithm{RSA_OAEP}, []ContentEncryption{A128GCM}) if err != nil { panic(err) } // Now we can decrypt and get back our original plaintext. An error here // would indicate that 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.Print(string(decrypted)) ``` -------------------------------- ### Go JWT: JSONWebToken.Claims Example (Multiple Destinations) Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/jwt Demonstrates deserializing JWT claims into multiple Go structs using the `Claims` method. This allows for mapping different parts of the JWT payload to distinct Go types, including a custom struct for specific fields like 'scopes'. ```Go raw := `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJpc3N1ZXIiLCJzY29wZXMiOlsiczEiLCJzMiJdLCJzdWIiOiJzdWJqZWN0In0.O9XxAYZsxXxWpTftO75vLpyYZ1g7FHxBvyvctGg3Ih0` tok, err := jwt.ParseSigned(raw, []jose.SignatureAlgorithm{jose.HS256}) if err != nil { fmt.Printf("parsing JWT: %s\n", err) return } out := jwt.Claims{} out2 := struct { Scopes []string `json:"scopes"` }{} if err := tok.Claims(sharedKey, &out, &out2); err != nil { fmt.Printf("validating claims: %s\n", err) return } fmt.Printf("iss: %s, sub: %s, scopes: %s\n", out.Issuer, out.Subject, strings.Join(out2.Scopes, ",")) ``` -------------------------------- ### Test jose-util with cram Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/jose-util@v4.1 Demonstrates how to run tests for the `jose-util` tool using the `cram` testing framework. This involves building the Go binary and then executing the `cram` test suite against it, ensuring the utility functions as expected. ```Shell go build && PATH=$PWD:$PATH cram -v jose-util.t ``` -------------------------------- ### Go func ParseSignedCompact Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1 ParseSignedCompact parses a message in JWS Compact Serialization. Validation fails if the JWS is signed with an algorithm that isn't in the provided list of signature algorithms. Applications should decide for themselves which signature algorithms are acceptable.If you're not sure which signature algorithms your application might receive, consult the documentation of the program which provides them or the protocol that you are implementing. You can also try getting an example JWS and decoding it with a tool like to see what its "alg" header parameter indicates. The signature on the JWS does not get validated during parsing. Call Verify() after parsing to validate the signature and obtain the payload. ```go func ParseSignedCompact( signature string, signatureAlgorithms []SignatureAlgorithm, ) (*JSONWebSignature, error) ``` -------------------------------- ### Go func ParseSigned Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1 ParseSigned parses a signed message in JWS Compact or JWS JSON Serialization. Validation fails if the JWS is signed with an algorithm that isn't in the provided list of signature algorithms. Applications should decide for themselves which signature algorithms are acceptable. If you're not sure which signature algorithms your application might receive, consult the documentation of the program which provides them or the protocol that you are implementing. You can also try getting an example JWS and decoding it with a tool like to see what its "alg" header parameter indicates. The signature on the JWS does not get validated during parsing. Call Verify() after parsing to validate the signature and obtain the payload. ```go func ParseSigned( signature string, signatureAlgorithms []SignatureAlgorithm, ) (*JSONWebSignature, error) ``` -------------------------------- ### Go func ParseDetached Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1 ParseDetached parses a signed message in compact serialization format with detached payload. Validation fails if the JWS is signed with an algorithm that isn't in the provided list of signature algorithms. Applications should decide for themselves which signature algorithms are acceptable. If you're not sure which signature algorithms your application might receive, consult the documentation of the program which provides them or the protocol that you are implementing. You can also try getting an example JWS and decoding it with a tool like to see what its "alg" header parameter indicates. The signature on the JWS does not get validated during parsing. Call Verify() after parsing to validate the signature and obtain the payload. ```go func ParseDetached( signature string, payload []byte, signatureAlgorithms []SignatureAlgorithm, ) (*JSONWebSignature, error) ``` -------------------------------- ### Test jose-util with Cram Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/jose-util This command sequence demonstrates how to test the `jose-util` utility using `cram`. It involves building the Go project to create the executable and then running `cram` tests, typically found in `jose-util.t`, ensuring the executable is in the PATH. ```Shell go build && PATH=$PWD:$PATH cram -v jose-util.t ``` -------------------------------- ### Go Struct Field JSON Tag 'string' Option Example Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/json Example of using the 'string' option in a Go JSON struct tag, which signals that a field's value should be stored as a JSON-encoded string within the main JSON output. ```Go Int64String int64 `json:",string"` ``` -------------------------------- ### cryptosigner Go Package API Reference Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1.1/cryptosigner Detailed API reference for the `cryptosigner` Go package, outlining its purpose, the `Opaque` function, its parameters, and return types, providing a comprehensive overview of its interface. ```APIDOC Package: cryptosigner Overview: Implements an OpaqueSigner that wraps a "crypto".Signer (https://godoc.org/crypto#Signer) Functions: Opaque(s crypto.Signer) jose.OpaqueSigner Description: Creates an OpaqueSigner from a "crypto".Signer Parameters: s: crypto.Signer - The cryptographic signer to be wrapped. Returns: jose.OpaqueSigner - An opaque signer compatible with the jose library. ``` -------------------------------- ### APIDOC: NewSigningKey Function Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1.1/jose-util/generator API documentation for the `NewSigningKey` function. It generates a keypair suitable for a corresponding `jose.SignatureAlgorithm`. ```APIDOC func NewSigningKey(alg jose.SignatureAlgorithm, bits int) (crypto.PublicKey, crypto.PrivateKey, error) ``` -------------------------------- ### Go-jose JSON Package API Reference Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/@v4.1.1/json Detailed API reference for functions and types within the `go-jose/go-jose/v4` package, including methods and their signatures. ```APIDOC Functions: Compact(dst, src) HTMLEscape(dst, src) Indent(dst, src, prefix, indent) Marshal(v) MarshalIndent(v, prefix, indent) Unmarshal(data, v) Types: type Decoder NewDecoder(r) (dec) Buffered() (dec) Decode(v) (dec) More() (dec) SetNumberType(t) (dec) Token() (dec) UseNumber() type Delim (d) String() type Encoder NewEncoder(w) (enc) Encode(v) type InvalidUTF8Error (e) Error() type InvalidUnmarshalError (e) Error() type Marshaler type MarshalerError (e) Error() type Number (n) Float64() (n) Int64() (n) String() type NumberUnmarshalType type RawMessage (m) MarshalJSON() (m) UnmarshalJSON(data) type SyntaxError (e) Error() type Token type UnmarshalFieldError (e) Error() type UnmarshalTypeError (e) Error() type Unmarshaler type UnsupportedTypeError (e) Error() type UnsupportedValueError (e) Error() ``` -------------------------------- ### Go-JOSE API Reference: Core Types and Methods Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/index This section outlines the key types and methods available within the go-jose library, covering functionalities like multi-signature verification, key algorithms, nonce sources, encrypters, signers, recipients, and signature options. It serves as a quick reference for the library's public interface. ```APIDOC JSONWebSignature: - (obj) VerifyMulti(verificationKey) Types: - KeyAlgorithm - NonceSource - OpaqueKeyDecrypter - OpaqueKeyEncrypter - OpaqueSigner - OpaqueVerifier - Recipient - Signature - SignatureAlgorithm - Signer: - NewMultiSigner(sigs, opts) - NewSigner(sig, opts) - SignerOptions: - (so) WithBase64(b64) - (so) WithContentType(contentType) - (so) WithCritical(names) - (so) WithHeader(k, v) - (so) WithType(typ) - SigningKey ``` -------------------------------- ### Importing Go-JOSE v4 Package in Go Source: https://pkg.go.dev/github.com/go-jose/go-jose/v4/index This snippet demonstrates the standard way to import the go-jose/go-jose/v4 package into a Go project. Importing this package grants access to its functionalities for JSON Web Signing and Encryption. ```Go import "github.com/go-jose/go-jose/v4" ```