### Complete PASETO Token Flow Example Source: https://github.com/bannable/paseto/blob/main/_autodocs/README.md This Ruby snippet demonstrates the full lifecycle of a PASETO token, including configuration, key generation, token creation, and verification. Ensure the Paseto gem is installed and necessary dependencies like RbNaCl and OpenSSL are met. ```ruby # 1. Initialize library configuration Paseto.configure do |config| config.decode.verify_exp = true config.decode.verify_aud = 'my-service' end # 2. Generate key (once, store securely) signing_key = Paseto::V4::Public.generate puts "Private key: #{signing_key.private_to_pem}" # 3. Create token claims = { 'user_id' => 42, 'email' => 'user@example.com' } footer = { 'kid' => signing_key.pid } token_string = signing_key.encode(claims, footer: footer) # 4. Send token to client (e.g., in response header) # 5. Client receives token and wants to verify received_token = token_string # 6. Pre-decode: check footer to find the right key token = Paseto::Token.parse(received_token) kid = token.footer['kid'] signing_key_pem = key_store.fetch(kid) # 7. Load verification key and decode verifier = Paseto::V4::Public.new(signing_key_pem) result = verifier.decode(received_token) # 8. Use verified claims user_id = result.claims['user_id'] email = result.claims['email'] ``` -------------------------------- ### Install Gem Dependencies Source: https://github.com/bannable/paseto/blob/main/README.md Run this command after checking out the repository to install necessary dependencies. ```shell bin/setup ``` -------------------------------- ### Install Gem Locally Source: https://github.com/bannable/paseto/blob/main/README.md Installs the Paseto gem onto your local machine. ```shell bundle exec rake install ``` -------------------------------- ### Configuration Source: https://github.com/bannable/paseto/blob/main/_autodocs/INDEX.md Provides examples of configuring the Paseto gem for token decoding, including claim verification rules and footer serialization. ```APIDOC ## Configuration ### Description Configure the Paseto gem for token decoding, including claim verification rules and footer serialization. ### Example ```ruby Paseto.configure do |config| config.decode.verify_exp = true config.decode.verify_aud = 'my-service' config.decode.verify_iss = /https:\/\/auth.*\.example\.com/ config.decode.footer_serializer = Paseto::Serializer::OptionalJson end ``` ``` -------------------------------- ### PASERK String Format Example Source: https://github.com/bannable/paseto/blob/main/_autodocs/architecture.md Illustrates the general format of a PASERK string, which includes version, type, algorithm, and data components. Examples show different variations like local, local-wrap, secret-pw, and pid types. ```plaintext k{version}.{type}.{algorithm}.{data} k4.local.pie.8qQp... k4.local-wrap.pie.8qQp... k4.secret-pw.hSmz... k4.pid.h5u7... ``` -------------------------------- ### Validator Usage Example Source: https://github.com/bannable/paseto/blob/main/_autodocs/architecture.md Demonstrates how to instantiate and verify a validator. Raises Paseto::ExpiredToken if the expiration claim is invalid. ```ruby Validator::Expiration.new(claims, options).verify ``` -------------------------------- ### Complete Workflow: Backup and Restore Signing Key Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-operations.md This example demonstrates a full workflow for backing up a signing key using password protection and then restoring it. It covers key generation, encrypted backup, and restoration. ```ruby # Scenario: Back up a signing key with password protection # 1. Create the signing key signer = Paseto::V4::Public.generate # 2. Export private key with password (for backup) backup_paserk = signer.pbkd( password: 'strong-password-here', options: { opslimit: :sensitive, memlimit: :sensitive } ) # 3. Store the backup (encrypted) config['signer_backup'] = backup_paserk # 4. Later, restore from backup restored_signer = Paseto::Paserk.from_paserk( paserk: config['signer_backup'], password: 'strong-password-here' ) # 5. Verify it works token = restored_signer.encode({'user' => 'alice'}) result = restored_signer.decode(token) ``` -------------------------------- ### Complete Paseto Decode Configuration Example Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-configure.md Demonstrates a comprehensive Paseto decode configuration, including footer serialization, expiration, not-before, issued-at, audience, issuer, subject, and token ID validation. ```ruby Paseto.configure do |config| # Use OptionalJson for footer deserialization (default) config.decode.footer_serializer = Paseto::Serializer::OptionalJson # Expiration validation (default: true) config.decode.verify_exp = true # Not-before validation (default: true) config.decode.verify_nbf = true # Issued-at validation (default: true) config.decode.verify_iat = true # Audience validation config.decode.verify_aud = ['service-1', 'service-2'] # Issuer validation with regex config.decode.verify_iss = /\Ahttps:\/\/auth(1|2)\.example\.com\z/ # Subject validation config.decode.verify_sub = 'user@example.com' # Token ID validation with proc config.decode.verify_jti = ->(jti) { jti.start_with?('jti-') } end # Later, use the configured defaults: key = Paseto::V4::Local.generate token = key.encode({'data' => 'value'}) result = key.decode(token) # Uses all configured defaults ``` -------------------------------- ### Example: Custom Issuer Validator with Domain Suffix Matching Source: https://github.com/bannable/paseto/blob/main/_autodocs/configuration.md Demonstrates using a custom proc validator for issuer verification during Paseto decoding. The example configures a validator to check if the issuer string ends with a specific domain suffix. ```ruby # With proc validator for domain suffix matching issuer_validator = ->(iss) { iss.end_with?('.example.com') } Paseto.configure do |config| config.decode.verify_iss = issuer_validator end token = key.encode({'iss' => 'auth.internal.example.com'}) result = key.decode(token) # Passes ``` -------------------------------- ### Paseto Decode Result Example Source: https://github.com/bannable/paseto/blob/main/_autodocs/types.md Demonstrates encoding a token and then decoding it to access claims and footer information. ```ruby key = Paseto::V4::Local.generate token = key.encode({'user' => 'alice'}, footer: {'kid' => 'key-1'}) result = key.decode(token) # => "alice", "exp"=>"...", "iat"=>"...", "nbf"=>"..."}, footer={"kid"=>"key-1"}> result.claims['user'] # => 'alice' result.footer['kid'] # => 'key-1' ``` -------------------------------- ### Example: Token with Multiple Audiences Source: https://github.com/bannable/paseto/blob/main/_autodocs/configuration.md Shows how to encode a token with multiple audiences and then decode it, verifying against an allowed list. The verification succeeds if there is an intersection between the token's audiences and the allowed list. ```ruby # Token with multiple audiences token = key.encode({'aud' => ['web', 'api', 'mobile']}) # Allowed list of audiences allowed_aud = ['api', 'mobile'] # Verification succeeds if there's intersection result = key.decode(token, verify_aud: allowed_aud) ``` -------------------------------- ### Generate a new Paseto V3 Local instance Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v3-local.md Use `generate` to create a new Local instance with a randomly generated 256-bit key. This is useful for starting new encryption contexts. ```ruby crypt = Paseto::V3::Local.generate token = crypt.encode({'foo' => 'bar'}) # => "v3.local.eyJ..." ``` -------------------------------- ### Get Raw Keypair Bytes Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-public.md Returns the raw keypair (private + public) as a 64-byte binary string. Raises an ArgumentError if no private key is available. ```ruby signer = Paseto::V4::Public.generate keypair = signer.to_bytes # => 64-byte string ``` -------------------------------- ### Generate a new Paseto::V4::Local instance Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-local.md Use `generate` to create a new Paseto::V4::Local instance with a randomly generated 256-bit key. This is useful for starting new encryption/decryption operations. ```ruby crypt = Paseto::V4::Local.generate token = crypt.encode({'foo' => 'bar'}) # => "v4.local.DhLZ..." ``` -------------------------------- ### Paseto::V4::Local.generate Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-local.md Creates a new Paseto::V4::Local instance with a randomly generated 256-bit key. This is useful for starting new encryption/decryption operations without managing keys manually. ```APIDOC ## Paseto::V4::Local.generate ### Description Creates a new Local instance with a randomly generated 256-bit key. ### Method `self.generate` ### Returns A new `Paseto::V4::Local` instance with a randomly generated key. ### Example ```ruby crypt = Paseto::V4::Local.generate token = crypt.encode({'foo' => 'bar'}) # => "v4.local.DhLZ..." ``` ``` -------------------------------- ### Get Raw Paseto V4 Local Key Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-local.md Retrieves the raw 256-bit key material as a 32-byte binary string. This is useful for direct key manipulation or when the key needs to be represented in its raw form. ```ruby crypt = Paseto::V4::Local.generate key_bytes = crypt.key # => "\x3f\x1a\x2e..." (32 bytes) ``` -------------------------------- ### Get raw PASETO token footer Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-token.md Use `raw_footer` to get the undecoded footer bytes as a binary string from a `Paseto::Token` object. ```ruby def raw_footer -> String end ``` -------------------------------- ### Paseto::V3::Local.initialize Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v3-local.md Initializes a Paseto::V3::Local instance with a provided 256-bit input key material. This allows for using a pre-determined key for encryption and decryption. ```APIDOC ## Paseto::V3::Local.initialize ### Description Initializes a Local instance with a 256-bit input key material. ### Method `initialize(ikm: String)` ### Parameters #### Path Parameters - **ikm** (String) - Required - 256-bit (32 bytes) input key material ### Raises - **ArgumentError**: ikm is not exactly 32 bytes ### Example ```ruby ikm = SecureRandom.bytes(32) crypt = Paseto::V3::Local.new(ikm: ikm) token = crypt.encode({'foo' => 'bar'}) ``` ``` -------------------------------- ### Generate and Get PASERK for Paseto V4 Public Key Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-public.md Generates a new Paseto V4 Public key and retrieves its full PASERK representation. Use this to get the key in a portable format. ```ruby signer = Paseto::V4::Public.generate signer.paserk # => "k4.secret.eyJw..." verifier = Paseto::V4::Public.new(signer.public_to_pem) verifier.paserk # => "k4.public.hJ8f..." ``` -------------------------------- ### Paseto Configuration Pattern for Decoding Source: https://github.com/bannable/paseto/blob/main/_autodocs/errors.md Shows how to set default decoding configurations, such as verifying expiration and audience, once globally. It then demonstrates decoding without explicit checks, relying on the defaults, and catching Paseto::ValidationError if claims validation fails. ```ruby # Set defaults once Paseto.configure do |config| config.decode.verify_exp = true config.decode.verify_aud = 'my-app' end # Decode without worrying about defaults begin result = key.decode(token) rescue Paseto::ValidationError => e # Claims validation failed log_validation_error(e) end ``` -------------------------------- ### Environment Variable Configuration for PASETO Source: https://github.com/bannable/paseto/blob/main/_autodocs/configuration.md Demonstrates how to integrate environment variables into PASETO configuration for audience, issuer, and subject validation. ```ruby Paseto.configure do |config| config.decode.verify_aud = ENV['PASETO_AUDIENCE'] || false config.decode.verify_iss = ENV['PASETO_ISSUER'] || false config.decode.verify_sub = ENV['PASETO_SUBJECT'] || false end ``` -------------------------------- ### Example: Validate JTI Format with UUID Regex Source: https://github.com/bannable/paseto/blob/main/_autodocs/configuration.md Provides an example of configuring JTI validation using a regular expression to ensure the token identifier matches a UUID format. The decode operation passes if the JTI conforms to the specified regex. ```ruby # Validate JTI format Paseto.configure do |config| config.decode.verify_jti = ->(jti) do UUID_REGEX.match?(jti) end end token = key.encode({'jti' => SecureRandom.uuid}) result = key.decode(token) # Passes if jti matches UUID format ``` -------------------------------- ### Initialize Paseto V3 Local with a specific key Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v3-local.md Initialize a Local instance with your own 256-bit (32-byte) key material. Ensure the input key is exactly 32 bytes to avoid errors. ```ruby ikm = SecureRandom.bytes(32) crypt = Paseto::V3::Local.new(ikm: ikm) token = crypt.encode({'foo' => 'bar'}) ``` -------------------------------- ### Paseto::V4::Local.initialize Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-local.md Initializes a Paseto::V4::Local instance with a provided 256-bit key material. This method requires the user to supply their own key for encryption and decryption. ```APIDOC ## Paseto::V4::Local.initialize ### Description Initializes a Local instance with a 256-bit input key material. ### Method `initialize(ikm: String)` ### Parameters #### Path Parameters - **ikm** (String) - Required - 256-bit (32 bytes) input key material ### Raises - **ArgumentError**: ikm is not exactly 32 bytes ### Example ```ruby ikm = SecureRandom.bytes(32) crypt = Paseto::V4::Local.new(ikm: ikm) token = crypt.encode({'foo' => 'bar'}) ``` ``` -------------------------------- ### Get Public-Only PASERK Representation Source: https://github.com/bannable/paseto/blob/main/_autodocs/types.md Generates the public-only PASERK representation for a key. ```ruby public_key_object.public_paserk ``` -------------------------------- ### Get Full PASERK Representation Source: https://github.com/bannable/paseto/blob/main/_autodocs/types.md Generates the full PASERK representation for a key. ```ruby key_object.paserk ``` -------------------------------- ### Get PASERK Public ID Source: https://github.com/bannable/paseto/blob/main/_autodocs/types.md Retrieves the PASERK identifier for a public key. ```ruby public_key.pid ``` -------------------------------- ### Initialize Paseto::V4::Local with a specific key Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-local.md Initialize a Paseto::V4::Local instance with a 256-bit (32 bytes) input key material. Ensure the provided key is exactly 32 bytes to avoid an ArgumentError. ```ruby ikm = SecureRandom.bytes(32) crypt = Paseto::V4::Local.new(ikm: ikm) token = crypt.encode({'foo' => 'bar'}) ``` -------------------------------- ### Initialize Paseto V4 Public from PEM or RbNaCl Key Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-public.md Initialize a Paseto::V4::Public instance using a PEM-encoded key string, an RbNaCl::SigningKey, or an RbNaCl::VerifyKey. This allows using existing keys for signing or verification. ```ruby # From PEM file pem = File.read('my_key.pem') signer = Paseto::V4::Public.new(pem) # From RbNaCl::SigningKey key = RbNaCl::SigningKey.generate signer = Paseto::V4::Public.new(key) # Public key only (verification only) verify_key = RbNaCl::VerifyKey.new(public_bytes) verifier = Paseto::V4::Public.new(verify_key) ``` -------------------------------- ### Get PASERK Secret ID Source: https://github.com/bannable/paseto/blob/main/_autodocs/types.md Retrieves the PASERK identifier for a private key. ```ruby private_key.sid ``` -------------------------------- ### Get PASERK Local ID Source: https://github.com/bannable/paseto/blob/main/_autodocs/types.md Retrieves the PASERK identifier for a local key. ```ruby local_key.lid ``` -------------------------------- ### Initialize Verifier with Public Key (v4 Public) Source: https://github.com/bannable/paseto/blob/main/README.md Initializes a Public key instance solely for verification using the signer's public key in PEM format. ```ruby verifier = Paseto::V4::Public.new(signer.public_to_pem) ``` -------------------------------- ### Get Raw Private Key Bytes Source: https://github.com/bannable/paseto/blob/main/_autodocs/types.md Retrieves the raw private key bytes. ```ruby private_key_object.to_bytes ``` -------------------------------- ### Paseto::V4::Public.initialize Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-public.md Initializes a Public instance from an Ed25519 key. This allows you to use existing keys for signing or verification. ```APIDOC ## Paseto::V4::Public.initialize ### Description Initializes a Public instance from an Ed25519 key. ### Method `initialize(key: String | RbNaCl::SigningKey | RbNaCl::VerifyKey)` ### Parameters #### Key Parameter - **key** (String, RbNaCl::SigningKey, or RbNaCl::VerifyKey) - Required - PEM/DER-encoded Ed25519 key or RbNaCl key object ### Raises - **ParseError**: Invalid PEM/DER encoding or format - **LucidityError**: Key is not Ed25519 type ### Example ```ruby # From PEM file pem = File.read('my_key.pem') signer = Paseto::V4::Public.new(pem) # From RbNaCl::SigningKey key = RbNaCl::SigningKey.generate signer = Paseto::V4::Public.new(key) # Public key only (verification only) verify_key = RbNaCl::VerifyKey.new(public_bytes) verifier = Paseto::V4::Public.new(verify_key) ``` ``` -------------------------------- ### Get Raw Public Key Bytes Source: https://github.com/bannable/paseto/blob/main/_autodocs/types.md Retrieves the raw public key bytes. ```ruby public_key_object.public_bytes ``` -------------------------------- ### Paseto::Token#initialize Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-token.md Initializes a Token object with payload, purpose, version, and optional footer data. ```APIDOC ## Paseto::Token#initialize ### Description Initializes a Token object with the provided payload, purpose, version, and an optional footer. This is used internally after a token has been parsed or when constructing a token from raw components. ### Method `initialize(payload: String, purpose: String, version: String, footer: String | Hash[String, untyped] = '')` ### Parameters #### Path Parameters - **payload** (String) - Required - Raw binary payload (after decryption/signing) - **purpose** (String) - Required - Token purpose (`'local'` or `'public'`) - **version** (String) - Required - PASETO version (`'v3'` or `'v4'`) - **footer** (String or Hash) - Optional - Default: `''` - Footer data ### Returns A new `Paseto::Token` instance. ### Raises - **UnsupportedToken**: Invalid version/purpose combination ### Example ```ruby token = Paseto::Token.new( payload: encrypted_bytes, purpose: 'local', version: 'v4', footer: {'kid' => 'key-1'} ) token.to_s # => "v4.local.eyJ...footer..." ``` ``` -------------------------------- ### Sign and Verify a Token (Asymmetric) Source: https://github.com/bannable/paseto/blob/main/_autodocs/README.md Illustrates how to generate an asymmetric key pair (signer), sign data into a token, and then verify the token using only the public key. This is suitable for scenarios where a trusted issuer needs to sign tokens for potentially untrusted verifiers. ```APIDOC ## Sign and Verify a Token (Asymmetric) ### Description This operation demonstrates how to sign data using an asymmetric key pair and then verify the signature using the corresponding public key. It's used for scenarios where a trusted party signs a token, and others can verify its authenticity without needing the private key. ### Method - `Paseto::V4::Public.generate` to create a new asymmetric key pair. - `signer.encode(claims)` to sign a token. - `verifier.decode(token)` to verify a token using a public key. ### Parameters #### `signer.encode` - **claims** (Hash) - The data to be included in the token. #### `verifier.decode` - **token** (String) - The PASETO token string to decode. ### Request Example ```ruby # Create keypair signer = Paseto::V4::Public.generate # Sign token token = signer.encode({'role' => 'admin'}) # => "v4.public.eyJ..." # Verify with public key only verifier = Paseto::V4::Public.new(signer.public_to_pem) result = verifier.decode(token) # => "admin", ...}, footer=nil> ``` ### Response #### Success Response - **result** (Paseto::Result) - An object containing the decoded claims and footer. - **claims** (Hash) - The claims extracted from the token. - **footer** (Object or nil) - The footer of the token, if present. #### Response Example ```json { "claims": { "role": "admin" }, "footer": null } ``` ``` -------------------------------- ### Initialize PASETO v3 Local Key with IKM Source: https://github.com/bannable/paseto/blob/main/README.md Initializes a PASETO v3 Local key instance with a specific 32-byte Implicit Key Material (IKM). Requires the 'openssl' gem. ```ruby ikm = SecureRandom.bytes(32) crypt = Paseto::V3::Local.new(ikm: ikm) ``` -------------------------------- ### Get Full PASERK Representation Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v3-local.md Obtains the full PASERK representation of a Paseto V3 Local key. This is a PASERK k3.local string. ```ruby crypt = Paseto::V3::Local.generate crypt.paserk # => "k3.local.tnVpN4t..." ``` -------------------------------- ### Typical PASETO Token Usage Pattern Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-token.md Demonstrates a common workflow for handling PASETO tokens, including parsing, accessing the footer for key identification, and decoding the claims. ```ruby # Get footer before decoding (avoids decrypting the payload) token = Paseto::Token.parse(token_string) puts "Token version: #{token.version}" puts "Token purpose: #{token.purpose}" puts "Footer: #{token.footer}" # Look up the key using footer information kid = token.footer['kid'] key = key_store.fetch(kid) # Now decode with the correct key claims = token.decode!(key) ``` -------------------------------- ### Get Compressed Public Key Bytes Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v3-public.md Retrieves the compressed public key as a binary string. This can be used for serialization or when a byte representation is needed. ```ruby signer = Paseto::V3::Public.generate bytes = signer.public_bytes # => 49-byte string verifier = Paseto::V3::Public.from_public_bytes(bytes) ``` -------------------------------- ### Get PASERK Public ID (pid) Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-public.md Returns the PASERK public ID (`k4.pid`) for the key. This ID is the same for both the signing key and its corresponding verification key. ```ruby signer = Paseto::V4::Public.generate signer.pid # => "k4.pid.5g4..." # Same for both signer and verifier verifier = Paseto::V4::Public.new(signer.public_to_pem) verifier.pid == signer.pid ``` -------------------------------- ### Basic Paseto v4 Usage Source: https://github.com/bannable/paseto/blob/main/README.md Demonstrates generating symmetric and asymmetric keys, encoding claims into a signed token with a footer, and decoding the token to retrieve claims and footer information. Note that decoded claims are not identical to original claims due to default claim additions. ```ruby claims = { "foo" => "bar", "baz" => 1, "time" => Time.now } symmetric = Paseto::V4::Local.generate asymmetric = Paseto::V4::Public.generate footer = {'kid' => asymmetric.pid} signed_token = asymmetric.encode(claims, footer: footer) # => "v4.public.eyJ..." result = asymmetric.decode(signed_token) # => "2022-12-..., "iat"=>"2022-12-..., # "nbf"=>"2022-12-21T10:00:00Z", "foo"=>"bar", "baz"=>1, "time"=>"2022-12-21T10:00:00Z"}, # footer={"kid"=>"k4.pid.Mu7prut6-zPCIkJ..."> result.claims == claims # => false result.claims['foo'] == 'bar' # => true ``` -------------------------------- ### Create and Decrypt a Token (Symmetric) Source: https://github.com/bannable/paseto/blob/main/_autodocs/README.md Demonstrates how to generate a symmetric key, encode claims into a token, and then decode and verify the token using the same key. This is useful for secure communication between two parties where a shared secret is feasible. ```APIDOC ## Create and Decrypt a Token (Symmetric) ### Description This operation allows for the creation and decryption of PASETO tokens using symmetric encryption. It involves generating a shared secret key, encoding data (claims) into a token, and then decoding and verifying that token using the same key. This is ideal for scenarios where two parties can securely share a secret key. ### Method - `Paseto::V4::Local.generate` to create a new symmetric key. - `crypt.encode(claims)` to create a token. - `crypt.decode(token)` to decrypt and verify a token. ### Parameters #### `crypt.encode` - **claims** (Hash) - The data to be included in the token. #### `crypt.decode` - **token** (String) - The PASETO token string to decode. ### Request Example ```ruby # Create key crypt = Paseto::V4::Local.generate # Create token with claims and expiration token = crypt.encode({'user_id' => 123}) # => "v4.local.eyJ..." # Decrypt and verify token result = crypt.decode(token) # => 123, "exp"=>"...", ...}, footer=nil> result.claims['user_id'] # => 123 ``` ### Response #### Success Response - **result** (Paseto::Result) - An object containing the decoded claims and footer. - **claims** (Hash) - The claims extracted from the token. - **footer** (Object or nil) - The footer of the token, if present. #### Response Example ```json { "claims": { "user_id": 123, "exp": "2023-10-27T10:00:00Z" }, "footer": null } ``` ``` -------------------------------- ### Get PASERK ID (sid or pid) Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-public.md Returns the appropriate PASERK ID for the key. Returns the `sid` for private keys and `pid` for public-key-only instances. ```ruby signer = Paseto::V4::Public.generate signer.id # => "k4.sid.y5x..." (if private key exists) verifier = Paseto::V4::Public.new(signer.public_to_pem) verifier.id # => "k4.pid.5g4..." ``` -------------------------------- ### Initialize a Paseto::Token object Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-token.md Use `Paseto::Token.new` to create a new token instance with payload, purpose, version, and optional footer. This is useful for constructing tokens programmatically. ```ruby def initialize( payload: String, purpose: String, version: String, footer: String | Hash[String, untyped] = '' ) -> void end ``` ```ruby token = Paseto::Token.new( payload: encrypted_bytes, purpose: 'local', version: 'v4', footer: {'kid' => 'key-1'} ) token.to_s # => "v4.local.eyJ...footer..." ``` -------------------------------- ### Get Raw Key Material Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v3-local.md Retrieves the raw 256-bit key material used for Paseto V3 Local operations. This is a 32-byte binary string. ```ruby crypt = Paseto::V3::Local.generate key_bytes = crypt.key # => "\x3f\x1a\x2e..." (32 bytes) ``` -------------------------------- ### Convert Paseto::Token to string Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-token.md Use the `to_s` method on a `Paseto::Token` object to get its complete string representation, which is equivalent to its `inspect` method. ```ruby def to_s -> String end ``` ```ruby token = Paseto::Token.parse("v4.public.eyJ...") token.to_s # => "v4.public.eyJ..." # Equivalent to: token.inspect # => "v4.public.eyJ..." ``` -------------------------------- ### Create Paseto V3 Public from public key bytes Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v3-public.md Create a `Paseto::V3::Public` instance for verification purposes only, using a 49-byte compressed secp384r1 public key. ```ruby signer = Paseto::V3::Public.generate public_bytes = signer.public_bytes verifier = Paseto::V3::Public.from_public_bytes(public_bytes) ``` -------------------------------- ### Paseto::V3::Public.new Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v3-public.md Initializes a Paseto::V3::Public instance from a provided secp384r1 EC key, which can be DER or PEM-encoded. This is used for both signing and verification. ```APIDOC ## Paseto::V3::Public.new ### Description Initializes a `Paseto::V3::Public` instance from a secp384r1 EC key. ### Method `initialize(key: String)` ### Parameters #### Path Parameters - **key** (String) - Required - DER or PEM-encoded secp384r1 EC key ### Raises - `CryptoError`: Invalid key format or OpenSSL error - `LucidityError`: Key is not secp384r1 curve or invalid curve - `InvalidKeyPair`: Key validation failed ### Example ```ruby # From PEM file pem = File.read('my_key.pem') signer = Paseto::V3::Public.new(pem) # Public key only (verification only) public_pem = File.read('public.pem') verifier = Paseto::V3::Public.new(public_pem) ``` ``` -------------------------------- ### Get PASETO token purpose Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-token.md Access the `purpose` attribute of a `Paseto::Token` object to retrieve the token's purpose string ('local' or 'public'). ```ruby def purpose -> String end ``` ```ruby token = Paseto::Token.parse("v4.public.eyJ...") token.purpose # => "public" ``` -------------------------------- ### Initialize Paseto V3 Public from PEM key Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v3-public.md Initialize a `Paseto::V3::Public` instance using a DER or PEM-encoded secp384r1 EC key. Supports both signing (private key) and verification (public key only). ```ruby # From PEM file pem = File.read('my_key.pem') signer = Paseto::V3::Public.new(pem) # Public key only (verification only) public_pem = File.read('public.pem') verifier = Paseto::V3::Public.new(public_pem) ``` -------------------------------- ### Get PASETO token version Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-token.md Access the `version` attribute of a `Paseto::Token` object to retrieve the PASETO version string (e.g., 'v3' or 'v4'). ```ruby def version -> String end ``` ```ruby token = Paseto::Token.parse("v4.public.eyJ...") token.version # => "v4" ``` -------------------------------- ### Protocol Version Pattern Usage Source: https://github.com/bannable/paseto/blob/main/_autodocs/architecture.md Demonstrates how to use Protocol Version instances for cryptographic operations like encryption and hashing. Requires instantiating the appropriate version object. ```ruby v4 = Protocol::Version4.instance plaintext = v4.crypt(key: encryption_key, nonce: nonce, payload: message) v3 = Protocol::Version3.instance digest = v3.digest(data, digest_size: 48) ``` -------------------------------- ### Handle Token Not Yet Active Source: https://github.com/bannable/paseto/blob/main/_autodocs/errors.md Raised when the token's `nbf` (not before) claim is in the future. This example shows how to catch `InactiveToken` for a token that is not yet active. ```ruby key = Paseto::V4::Local.generate claims = { 'nbf' => (Time.now + 1).iso8601 } # Not yet active token = key.encode!(claims) begin key.decode(token) rescue Paseto::InactiveToken puts "Token is not yet active" end ``` -------------------------------- ### Initialize PASETO v4 Local Key with IKM Source: https://github.com/bannable/paseto/blob/main/README.md Initializes a PASETO v4 Local key instance with a specific 32-byte Implicit Key Material (IKM). Requires the 'rbnacl' gem. ```ruby ikm = SecureRandom.bytes(32) crypt = Paseto::V4::Local.new(ikm: ikm) ``` -------------------------------- ### Handle Expired Token Source: https://github.com/bannable/paseto/blob/main/_autodocs/errors.md Raised when the token's `exp` (expiration) claim is in the past. This example demonstrates catching `ExpiredToken` and how to skip the expiration check. ```ruby key = Paseto::V4::Local.generate claims = { 'exp' => (Time.now - 1).iso8601 } # Already expired token = key.encode!(claims) begin key.decode(token) rescue Paseto::ExpiredToken puts "Token has expired" end # To skip expiration check: result = key.decode(token, verify_exp: false) ``` -------------------------------- ### Detect Tampered or Corrupted Token Source: https://github.com/bannable/paseto/blob/main/_autodocs/errors.md Raised when authentication tag verification fails during decryption. This example demonstrates how to catch `InvalidAuthenticator` when a token has been tampered with or corrupted. ```ruby key = Paseto::V4::Local.generate token = key.encode({'data' => 'value'}) # Tamper with the token corrupted_token = token[0..-2] + 'X' begin key.decode(corrupted_token) rescue Paseto::InvalidAuthenticator puts "Token was tampered with or corrupted" end ``` -------------------------------- ### Key Generation Source: https://github.com/bannable/paseto/blob/main/_autodocs/INDEX.md Demonstrates how to generate symmetric and asymmetric keys for PASETO v4 and v3. ```APIDOC ## Key Generation ### Description Generate symmetric and asymmetric keys for PASETO v4 and v3. ### Symmetric Keys ```ruby local_v4 = Paseto::V4::Local.generate local_v3 = Paseto::V3::Local.generate ``` ### Asymmetric Keys ```ruby public_v4 = Paseto::V4::Public.generate public_v3 = Paseto::V3::Public.generate ``` ``` -------------------------------- ### Get PASERK Secret ID (sid) Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-public.md Returns the PASERK secret ID (`k4.sid`) for the key if it is a private key. Raises an ArgumentError if no private key is available. ```ruby signer = Paseto::V4::Public.generate signer.sid # => "k4.sid.y5x..." ``` -------------------------------- ### Generate Local and Public Keys (V4 and V3) Source: https://github.com/bannable/paseto/blob/main/_autodocs/INDEX.md Demonstrates how to generate symmetric (local) and asymmetric (public) keys for both V4 and V3 PASETO protocols. ```ruby # Symmetric keys local_v4 = Paseto::V4::Local.generate local_v3 = Paseto::V3::Local.generate # Asymmetric keys public_v4 = Paseto::V4::Public.generate public_v3 = Paseto::V3::Public.generate ``` -------------------------------- ### Get Raw Public Key Bytes Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-public.md Returns the raw public key as a 32-byte binary string. This can be used to create a verification key using `from_public_bytes`. ```ruby signer = Paseto::V4::Public.generate bytes = signer.public_bytes # => "\x1f\x4a\x2e..." (32 bytes) # Create verification key from bytes verifier = Paseto::V4::Public.from_public_bytes(bytes) ``` -------------------------------- ### Create Paseto V4 Public from Keypair Bytes Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-public.md Use `from_keypair` to create a Paseto::V4::Public instance directly from 64-byte Ed25519 keypair bytes. This is useful when keypairs are managed externally. ```ruby keypair_bytes = RbNaCl::SigningKey.generate.keypair_bytes public = Paseto::V4::Public.from_keypair(keypair_bytes) ``` -------------------------------- ### Get Raw Private Key Scalar Bytes Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v3-public.md Retrieves the raw private key scalar as a 48-byte binary string. This is a low-level representation of the private key. ```ruby signer = Paseto::V3::Public.generate scalar = signer.to_bytes # => 48-byte string ``` -------------------------------- ### Get Paseto V3 Local ID Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v3-local.md Retrieves the PASERK local ID (k3.lid) for a Paseto V3 Local key. This identifier is useful for referencing the key. ```ruby crypt = Paseto::V3::Local.generate crypt.lid # => "k3.lid.uGj..." ``` -------------------------------- ### Reset Decode Configuration to Defaults Source: https://github.com/bannable/paseto/blob/main/_autodocs/configuration.md Demonstrates how to reset all global decode configuration settings back to their default values using the `reset!` method. ```ruby Paseto.config.reset! # Resets decode configuration to all defaults ``` -------------------------------- ### Get Full Paseto V4 Local PASERK Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-local.md Retrieves the complete PASERK representation of the Paseto V4 Local key. The output is a string in the 'k4.local' format. ```ruby crypt = Paseto::V4::Local.generate crypt.paserk # => "k4.local.tnVpN4t..." ``` -------------------------------- ### Initialize PASETO v3 Public Key from PEM Source: https://github.com/bannable/paseto/blob/main/README.md Initializes a PASETO v3 Public key instance from a PEM- or DER-encoded secp384r1 key. Requires the 'openssl' gem. ```ruby signer = Paseto::V3::Public.new(signer.private_to_pem) ``` -------------------------------- ### Get Paseto V4 Local ID (id alias) Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-local.md An alias for the `lid` method, this returns the PASERK local ID for the Paseto V4 Local key. ```ruby crypt = Paseto::V4::Local.generate crypt.id # => "k4.lid.uGj..." ``` -------------------------------- ### Default PASETO Configuration Source: https://github.com/bannable/paseto/blob/main/_autodocs/configuration.md Shows the default configuration settings for PASETO, including validation rules for claims and footer deserialization. ```ruby { footer_serializer: Paseto::Serializer::OptionalJson, verify_exp: true, verify_nbf: true, verify_iat: true, verify_iss: false, verify_aud: false, verify_sub: false, verify_jti: false } ``` -------------------------------- ### Get Paseto V4 Local ID (lid) Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-local.md Retrieves the PASERK local ID for the Paseto V4 Local key. This identifier is a string in the 'k4.lid' format. ```ruby crypt = Paseto::V4::Local.generate crypt.lid # => "k4.lid.uGj..." ``` -------------------------------- ### Get raw PASETO token payload Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-token.md Use `raw_payload` to retrieve the raw, undecrypted, or unsigned payload bytes as a binary string from a `Paseto::Token` object. ```ruby def raw_payload -> String end ``` -------------------------------- ### Create Paseto V4 Public from Public Key Bytes Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-public.md Use `from_public_bytes` to create a Paseto::V4::Public instance for verification purposes only, using 32-byte Ed25519 public key bytes. This is suitable when you only have the public key. ```ruby public_bytes = signer.public_bytes verifier = Paseto::V4::Public.from_public_bytes(public_bytes) result = verifier.decode(token) ``` -------------------------------- ### key Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v4-local.md Retrieves the raw 256-bit key material used by the Paseto V4 Local instance. ```APIDOC ## key ### Description Returns the raw 256-bit key material that the Paseto V4 Local instance uses for encryption and decryption. ### Method `key` ### Returns A binary string representing the 32-byte secret key. ### Example ```ruby # Assuming 'crypt' is an instance of Paseto::V4::Local key_bytes = crypt.key # key_bytes will be a 32-byte binary string ``` ``` -------------------------------- ### Get PASETO Token Type Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-token.md Returns the class of key that is required to decode the PASETO token. This indicates whether the token is for local (symmetric) or public (asymmetric) use. ```ruby token = Paseto::Token.parse("v4.public.eyJ...") token.type # => Paseto::V4::Public token2 = Paseto::Token.parse("v4.local.eyJ...") token2.type # => Paseto::V4::Local ``` -------------------------------- ### Get PASETO token header Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-token.md Access the `header` attribute of a `Paseto::Token` object to retrieve the token's header string, formatted as 'version.purpose' (e.g., 'v4.public'). ```ruby def header -> String end ``` ```ruby token = Paseto::Token.parse("v4.public.eyJ...") token.header # => "v4.public" ``` -------------------------------- ### Sign and Verify a Token (Asymmetric) Source: https://github.com/bannable/paseto/blob/main/_autodocs/README.md Generates an asymmetric key pair, signs a token with the private key, and then verifies it using the public key. Suitable for asymmetric signing and verification. ```ruby # Create keypair signer = Paseto::V4::Public.generate # Sign token token = signer.encode({'role' => 'admin'}) # => "v4.public.eyJ..." # Verify with public key only verifier = Paseto::V4::Public.new(signer.public_to_pem) result = verifier.decode(token) # => "admin", ...}, footer=nil> ``` -------------------------------- ### Handle ImmatureToken Exception Source: https://github.com/bannable/paseto/blob/main/_autodocs/errors.md Shows how to catch the ImmatureToken error, which is raised when a token's issued-at claim is in the future. This example also demonstrates skipping the issued-at check. ```ruby key = Paseto::V4::Local.generate claims = { 'iat' => (Time.now + 1).iso8601 } # Issued in the future? token = key.encode!(claims) begin key.decode(token) rescue Paseto::ImmatureToken puts "Token issued in the future" end # To skip issued-at check: result = key.decode(token, verify_iat: false) ``` -------------------------------- ### Generate a new Paseto V3 Public keypair Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v3-public.md Use `Paseto::V3::Public.generate` to create a new instance with a randomly generated secp384r1 keypair. This is useful for creating new signers. ```ruby signer = Paseto::V3::Public.generate token = signer.encode({'admin' => true}) # => "v3.public.eyJ..." ``` -------------------------------- ### Handle Invalid Key for Algorithm Source: https://github.com/bannable/paseto/blob/main/_autodocs/errors.md Raised when a key is not valid for the algorithm, such as using an off-curve EC key or invalid key material. This example shows catching `InvalidKeyPair`. ```ruby # This might raise InvalidKeyPair if the key is invalid begin key = Paseto::V3::Public.new(invalid_der) rescue Paseto::InvalidKeyPair puts "Key is not valid for the algorithm" end ``` -------------------------------- ### Handle Invalid Signature or Wrong Key Source: https://github.com/bannable/paseto/blob/main/_autodocs/errors.md Raised when signature verification fails during verification. This example shows how to catch `InvalidSignature` when a token has been tampered with or verified with the wrong key. ```ruby signer = Paseto::V4::Public.generate token = signer.encode({'data' => 'value'}) # Try to verify with a different key other_key = Paseto::V4::Public.generate begin other_key.decode(token) rescue Paseto::InvalidSignature puts "Signature doesn't match - wrong key or tampered token" end ``` -------------------------------- ### Run Standalone Tests (v3, OpenSSL-only) Source: https://github.com/bannable/paseto/blob/main/README.md Executes the test suite using the OpenSSL cryptographic backend. ```shell bundle exec rspec ``` -------------------------------- ### Interactive Prompt Source: https://github.com/bannable/paseto/blob/main/README.md Opens an interactive Ruby console for experimenting with the gem. ```shell bin/console ``` -------------------------------- ### Paseto::V3::Local.generate Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v3-local.md Creates a new Paseto::V3::Local instance with a randomly generated 256-bit key. This is useful for initiating a new encryption context. ```APIDOC ## Paseto::V3::Local.generate ### Description Creates a new Local instance with a randomly generated 256-bit key. ### Method `self.generate` ### Returns A new `Paseto::V3::Local` instance with a randomly generated key. ### Example ```ruby crypt = Paseto::V3::Local.generate token = crypt.encode({'foo' => 'bar'}) # => "v3.local.eyJ..." ``` ``` -------------------------------- ### Configure PASETO Decode Options Source: https://github.com/bannable/paseto/blob/main/_autodocs/INDEX.md Sets global configuration options for PASETO token decoding, including claim verification rules and footer serialization. ```ruby Paseto.configure do |config| config.decode.verify_exp = true config.decode.verify_aud = 'my-service' config.decode.verify_iss = /https:\/\/auth.*\.example\.com/ config.decode.footer_serializer = Paseto::Serializer::OptionalJson end ``` -------------------------------- ### Get Public PASERK for Paseto V3 Public Key Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v3-public.md Generates a new Paseto V3 public key and retrieves its public-only PASERK representation. Use this when you only need to share the public key component. ```ruby signer = Paseto::V3::Public.generate signer.public_paserk # => "k3.public.hJ8f..." ``` -------------------------------- ### Get PASERK Public ID (PID) Source: https://github.com/bannable/paseto/blob/main/_autodocs/api-reference/paseto-v3-public.md Retrieves the PASERK public ID (k3.pid) for a PASETO V3 Public key instance. This ID is used for identifying public keys within the PASERK system. ```ruby signer = Paseto::V3::Public.generate signer.pid # => "k3.pid.5g4..." verifier = Paseto::V3::Public.new(signer.public_to_pem) verifier.pid == signer.pid # => true ``` -------------------------------- ### Wrap and Unwrap Symmetric Keys Source: https://github.com/bannable/paseto/blob/main/_autodocs/INDEX.md Demonstrates symmetric key wrapping for secure key transport using a wrapping key. ```ruby # Wrap a key with another key wrapped = wrapping_key.wrap(secret_key) recovered = wrapping_key.unwrap(wrapped) ```