Class ApiKeyGenerator

java.lang.Object
com.codename1.backend.security.apikey.ApiKeyGenerator

public final class ApiKeyGenerator extends Object

Makes API keys: a prefix, then 32 random bytes as base64url.

GeneratedApiKey made = new ApiKeyGenerator("acme_").generate("ci-bot", "deploy");

The prefix says what the string is. A secret scanner can find a leaked key by it, a person can tell a key from a token by it, and a chain that takes both API keys and JWTs as bearer credentials tells them apart by it.

A key is 256 random bits, so its SHA-256 is as hard to reverse as the key is to guess. That is why a plain hash is what is stored, and not the slow, salted one a password needs: there is nothing here to try a dictionary against, and the lookup runs on every request.

  • Field Details

  • Constructor Details

    • ApiKeyGenerator

      public ApiKeyGenerator()
    • ApiKeyGenerator

      public ApiKeyGenerator(String prefix)
      Parameters:
      prefix - what every key starts with: letters, digits and _
  • Method Details

    • checkPrefix

      public static String checkPrefix(String prefix)
      Refuses a prefix that is empty or holds anything but letters, digits and underscores.
    • getPrefix

      public String getPrefix()
    • generate

      public GeneratedApiKey generate(String owner, String... scopes)
      A new key for owner, granting scopes.
    • hash

      public static String hash(String plaintext)
      The lowercase hexadecimal SHA-256 of a key: what is stored, and what a presented key is looked up by.