com.unbound.provider.SecretKeyFactory 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.KeyFactorySpec;
import com.dyadicsec.provider.KeyParameters;
import com.unbound.provider.kmip.KMIP;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactorySpi;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.ProviderException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
public class SecretKeyFactory extends SecretKeyFactorySpi
{
private int kmipAlg;
private Partition partition;
private KeyParameters keyParameter = null;
SecretKeyFactory(Partition partition, int kmipAlg)
{
this.partition = partition;
this.kmipAlg = kmipAlg;
}
@Override
protected SecretKey engineGenerateSecret(KeySpec keySpec) throws InvalidKeySpecException
{
if (keySpec instanceof KeyFactorySpec)
{
keyParameter = ((KeyFactorySpec)keySpec).getKeyParams();
keySpec = ((KeyFactorySpec)keySpec).getOriginal();
}
else keyParameter = null;
if (keySpec == null) throw new InvalidKeySpecException("keySpec == null");
if (keySpec instanceof SecretKeySpec)
{
byte[] keyValue = ((SecretKeySpec) keySpec).getEncoded();
int bitSize = keyValue.length * 8;
if (kmipAlg==KMIP.CryptographicAlgorithm.AES)
{
if (bitSize != 128 && bitSize != 192 && bitSize != 256) throw new InvalidKeySpecException("Wrong key size: must be equal to 128, 192 or 256");
}
else // hmac
{
if (bitSize < 8 || bitSize > 2048 || (bitSize % 8)!=0) throw new InvalidKeySpecException("Wrong key size");
}
try
{
UBSecretKey secretKey = new UBSecretKey(partition, kmipAlg);
secretKey.register(keyParameter, keyValue, null);
return secretKey;
}
catch (Exception e) { throw new ProviderException(e); }
}
throw new InvalidKeySpecException("Must use SecretKeySpec; was " + keySpec.getClass().getName());
}
@Override
protected KeySpec engineGetKeySpec(SecretKey secretKey, Class> aClass) throws InvalidKeySpecException
{
throw new InvalidKeySpecException("Could not encode key");
}
@Override
protected SecretKey engineTranslateKey(SecretKey secretKey) throws InvalidKeyException
{
if (secretKey instanceof UBSecretKey) return secretKey;
throw new InvalidKeyException("secretKey must be instance of UBSecretKey");
}
// --------------------- Sub-classes ---------------------------
public static final class AES extends SecretKeyFactory { public AES(Partition partition) { super(partition, KMIP.CryptographicAlgorithm.AES); } }
public static final class Hmac extends SecretKeyFactory { public Hmac(Partition partition) { super(partition, KMIP.CryptographicAlgorithm.HMAC_SHA256); } }
}