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

com.unbound.provider.UBECKeyFactory 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.ECPrivateKeyObject;
import com.unbound.client.Partition;
import com.unbound.common.crypto.SystemProvider;

import java.security.*;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.*;

public final class UBECKeyFactory extends KeyFactorySpi
{
  private final Partition partition;
  private KeyParameters keyParameter = null;

  UBECKeyFactory(Partition partition)
  {
    this.partition = partition;
  }

// --------------------- interface -----------------
  @Override
  protected PublicKey engineGeneratePublic(KeySpec keySpec) throws InvalidKeySpecException
  {
    return SystemProvider.KeyFactory.getInstance("EC").generatePublic(keySpec);
  }

  @Override
  protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpecException
  {
    if (keySpec instanceof KeyFactorySpec)
    {
      keyParameter = ((KeyFactorySpec)keySpec).getKeyParams();
      keySpec = ((KeyFactorySpec)keySpec).getOriginal();
    }

    if (keySpec == null) throw new InvalidKeySpecException("keySpec == null");

    if ((keySpec instanceof ECPrivateKeySpec) || (keySpec instanceof PKCS8EncodedKeySpec))
    {
      ECPrivateKey keyValue = (ECPrivateKey)SystemProvider.KeyFactory.getInstance("EC").generatePrivate(keySpec);
      ECPrivateKeyObject object = partition.importEcKey(null, keyValue, keyParameter);
      return new UBECPrivateKey(object);
    }

    throw new InvalidKeySpecException("Must use ECPrivateKeySpec or PKCS8EncodedKeySpec; was " + keySpec.getClass().getName());
  }

  @Override
  protected  T engineGetKeySpec(Key key, Class keySpec) throws InvalidKeySpecException
  {
    if ((key == null) || (keySpec == null)) throw new InvalidKeySpecException("key and keySpec must not be null");

    if (key instanceof ECPublicKey && X509EncodedKeySpec.class.isAssignableFrom(keySpec))
    {
      return SystemProvider.KeyFactory.getInstance("EC").getKeySpec(key, keySpec);
    }

    if (key instanceof ECPublicKey && ECPublicKeySpec.class.isAssignableFrom(keySpec))
    {
      return (T) new ECPublicKeySpec(((ECPublicKey)key).getW(), ((ECPublicKey)key).getParams());
    }

    throw new InvalidKeySpecException("Could not encode key");
  }

  @Override
  protected Key engineTranslateKey(Key key) throws InvalidKeyException
  {
    return key;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy