package io.jsonwebtoken.security; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.lang.Assert; import io.jsonwebtoken.lang.Classes; import javax.crypto.SecretKey; import java.security.KeyPair; /** * Utility class for securely generating {@link SecretKey}s and {@link KeyPair}s. * * @since 0.10.0 */ public final class Keys { private static final String MAC = "io.jsonwebtoken.impl.crypto.MacProvider"; private static final String RSA = "io.jsonwebtoken.impl.crypto.RsaProvider"; private static final String EC = "io.jsonwebtoken.impl.crypto.EllipticCurveProvider"; private static final Class[] SIG_ARG_TYPES = new Class[]{SignatureAlgorithm.class}; //prevent instantiation private Keys() { } /* public static final int bitLength(Key key) throws IllegalArgumentException { Assert.notNull(key, "Key cannot be null."); if (key instanceof SecretKey) { byte[] encoded = key.getEncoded(); return Arrays.length(encoded) * 8; } else if (key instanceof RSAKey) { return ((RSAKey)key).getModulus().bitLength(); } else if (key instanceof ECKey) { return ((ECKey)key).getParams().getOrder().bitLength(); } throw new IllegalArgumentException("Unsupported key type: " + key.getClass().getName()); } */ /** * Returns a new {@link SecretKey} with a key length suitable for use with the specified {@link SignatureAlgorithm}. * *
JWA Specification (RFC 7518), Section 3.2 * requires minimum key lengths to be used for each respective Signature Algorithm. This method returns a * secure-random generated SecretKey that adheres to the required minimum key length. The lengths are:
* *Algorithm | *Key Length | *
---|---|
HS256 | *256 bits (32 bytes) | *
HS384 | *384 bits (48 bytes) | *
HS512 | *512 bits (64 bytes) | *
If the {@code alg} argument is an RSA algorithm, a KeyPair is generated based on the following:
* *JWA Algorithm | *Key Size | *
---|---|
RS256 | *2048 bits | *
PS256 | *2048 bits | *
RS384 | *3072 bits | *
PS256 | *3072 bits | *
RS512 | *4096 bits | *
PS512 | *4096 bits | *
If the {@code alg} argument is an Elliptic Curve algorithm, a KeyPair is generated based on the following:
* *JWA Algorithm | *Key Size | *JWA Curve Name | *ASN1 OID Curve Name | *
---|---|---|---|
EC256 | *256 bits | *{@code P-256} | *{@code secp256r1} | *
EC384 | *384 bits | *{@code P-384} | *{@code secp384r1} | *
EC512 | *512 bits | *{@code P-512} | *{@code secp521r1} | *