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

com.unbound.provider.UBSecretKeyGenerator Maven / Gradle / Ivy

Go to download

This is a collection of JAVA libraries that implement Unbound cryptographic classes for JAVA provider, PKCS11 wrapper, cryptoki, and advapi

There is a newer version: 42761
Show newest version
package com.unbound.provider;

import com.unbound.client.*;

import javax.crypto.KeyGeneratorSpi;
import javax.crypto.SecretKey;
import java.security.*;
import java.security.spec.AlgorithmParameterSpec;

public class UBSecretKeyGenerator extends KeyGeneratorSpi
{
  private final Partition partition;
  private final ObjectType type;
  private int bitSize;
  private KeyParameters keyParameter = null;

  UBSecretKeyGenerator(Partition partition, ObjectType type)
  {
    this.partition = partition;
    this.type = type;
    if (type==ObjectType.AES) bitSize = 128;
    else if (type==ObjectType.DES3) bitSize = 192;
  }

  @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 (type== ObjectType.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()
  {
    SecretKeyObject object = partition.generateSecretKey(null, type, bitSize, keyParameter);
    return new UBSecretKey(object);
  }

  // ---------------------------- Sub-classes -----------------------
  public static final class AES extends UBSecretKeyGenerator
  { public AES(Partition partition) { super(partition, ObjectType.AES); } }
  public static final class DES3 extends UBSecretKeyGenerator
  { public DES3(Partition partition) { super(partition, ObjectType.DES3); } }
  public static final class Hmac extends UBSecretKeyGenerator
  { public Hmac(Partition partition) { super(partition, ObjectType.GenericSecret); } }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy