Backend API. Server-side code: this runs in a Codename One backend, not in the app on the device.
public final class ApiKeyGenerator
- Object
- ApiKeyGenerator
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.
Fields
public static final String DEFAULT_PREFIX = "cn1_" | The prefix unless another is given. |
Constructors
public ApiKeyGenerator() | |
public ApiKeyGenerator(String prefix) |
Methods
public static String checkPrefix(String prefix) | Refuses a prefix that is empty or holds anything but letters, digits and underscores. |
public String getPrefix() | |
public GeneratedApiKey generate(String owner, String... scopes) | A new key for owner, granting scopes. |
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. |
Inherited methods
Field details
DEFAULT_PREFIX
public static final String DEFAULT_PREFIX = "cn1_"The prefix unless another is given.
Constructor details
ApiKeyGenerator
public ApiKeyGenerator()ApiKeyGenerator
public ApiKeyGenerator(String prefix)Parameters
prefixString- 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.