com.unbound.provider.SecretKeyGenerator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of unbound-java-provider Show documentation
Show all versions of unbound-java-provider Show documentation
This is a collection of JAVA libraries that implement Unbound cryptographic classes for JAVA provider, PKCS11 wrapper, cryptoki, and advapi
package com.unbound.provider;
import com.dyadicsec.provider.KeyGenSpec;
import com.dyadicsec.provider.KeyParameters;
import com.unbound.provider.kmip.KMIP;
import javax.crypto.KeyGeneratorSpi;
import javax.crypto.SecretKey;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidParameterException;
import java.security.ProviderException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
public class SecretKeyGenerator extends KeyGeneratorSpi
{
private int bitSize;
private int kmipAlg;
private Partition partition;
private KeyParameters keyParameter = null;
SecretKeyGenerator(Partition partition, int kmipAlg)
{
this.partition = partition;
this.kmipAlg = kmipAlg;
}
@Override
protected void engineInit(SecureRandom secureRandom) { }
@Override
protected void engineInit(AlgorithmParameterSpec algorithmParameterSpec, SecureRandom secureRandom) throws InvalidAlgorithmParameterException
{
if (!(algorithmParameterSpec instanceof KeyGenSpec)) throw new InvalidAlgorithmParameterException("Secret key generation does not take any parameters");
keyParameter = ((KeyGenSpec)algorithmParameterSpec).getKeyParams();
engineInit(((KeyGenSpec)algorithmParameterSpec).getBitSize(), secureRandom);
}
@Override
protected void engineInit(int bitSize, SecureRandom secureRandom)
{
if (kmipAlg==KMIP.CryptographicAlgorithm.AES)
{
if (bitSize != 128 && bitSize != 192 && bitSize != 256) throw new InvalidParameterException("Wrong key size: must be equal to 128, 192 or 256");
}
else // HMAC
{
if (bitSize < 8 || bitSize > 2048 || (bitSize % 8)!=0) throw new InvalidParameterException("Wrong key size");
}
this.bitSize = bitSize;
}
@Override
protected SecretKey engineGenerateKey()
{
UBSecretKey secretKey = new UBSecretKey(partition, kmipAlg);
try
{
secretKey.generate(keyParameter, bitSize);
}
catch (IOException e)
{
throw new ProviderException(e);
}
return secretKey;
}
// ---------------------------- Sub-classes -----------------------
public static final class AES extends SecretKeyGenerator { public AES(Partition partition) { super(partition, KMIP.CryptographicAlgorithm.AES); } }
public static final class Hmac extends SecretKeyGenerator { public Hmac(Partition partition) { super(partition, KMIP.CryptographicAlgorithm.HMAC_SHA256); } }
}