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

com.unbound.provider.ECKeyFactory 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.dyadicsec.provider.KeyFactorySpec;
import com.dyadicsec.provider.KeyParameters;
import com.unbound.common.crypto.SystemProvider;

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

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

  ECKeyFactory(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))
    {
      try
      {
        UBECPrivateKey key = new UBECPrivateKey(partition);
        key.register(keyParameter, keySpec);
        return key;
      }
      catch (Exception e) { throw new InvalidKeySpecException(e); }
    }
    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