All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.nimbusds.jose.jwk.gen.OctetSequenceKeyGenerator Maven / Gradle / Ivy

Go to download

Java library for Javascript Object Signing and Encryption (JOSE) and JSON Web Tokens (JWT)

There is a newer version: 9.47
Show newest version
/*
 * nimbus-jose-jwt
 *
 * Copyright 2012-2016, Connect2id Ltd and contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
 * this file except in compliance with the License. You may obtain a copy of the
 * License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed
 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

package com.nimbusds.jose.jwk.gen;


import java.security.SecureRandom;

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.jwk.OctetSequenceKey;
import com.nimbusds.jose.util.Base64URL;


/**
 * Octet sequence JSON Web Key (JWK) generator.
 *
 * @author Vladimir Dzhuvinov
 * @author Justin Cranford
 * @version 2023-01-02
 */
public class OctetSequenceKeyGenerator extends JWKGenerator {
	
	
	/**
	 * The minimum size of generated keys.
	 */
	public static final int MIN_KEY_SIZE_BITS = 112;
	
	
	/**
	 * The key size, in bits.
	 */
	private final int size;

	
	/**
	 * Creates a new octet sequence JWK generator.
	 *
	 * @param size The key size, in bits. Must be at least 112 bits long
	 *             for sufficient entropy.
	 */
	public OctetSequenceKeyGenerator(final int size) {
		if (size < MIN_KEY_SIZE_BITS) {
			throw new IllegalArgumentException("The key size must be at least " + MIN_KEY_SIZE_BITS + " bits");
		}
		if (size % 8 != 0) {
			throw new IllegalArgumentException("The key size in bits must be divisible by 8");
		}
		this.size = size;
	}

	
	@Override
	public OctetSequenceKey generate()
		throws JOSEException {
		
		byte[] keyMaterial = new byte[size / 8];
		
		if (secureRandom != null) {
			secureRandom.nextBytes(keyMaterial);
		} else {
			// The default random gen
			new SecureRandom().nextBytes(keyMaterial);
		}
		
		OctetSequenceKey.Builder builder = new OctetSequenceKey.Builder(Base64URL.encode(keyMaterial))
			.keyUse(use)
			.keyOperations(ops)
			.algorithm(alg)
			.keyStore(keyStore);
		
		if (x5tKid) {
			builder.keyIDFromThumbprint();
		} else {
			builder.keyID(kid);
		}
		
		return builder.build();
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy