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

com.unbound.provider.RSAKeyFactory 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.RSAPublicKey;
import java.security.spec.*;

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

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

// --------------------- interface -----------------

  @Override
  protected PublicKey engineGeneratePublic(KeySpec keySpec) throws InvalidKeySpecException
  {
    return SystemProvider.KeyFactory.getInstance("RSA").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 RSAPrivateCrtKeySpec) || (keySpec instanceof PKCS8EncodedKeySpec))
    {
      try
      {
        UBRSAPrivateKey key = new UBRSAPrivateKey(partition);
        key.register(keyParameter, keySpec);
        return key;
      }
      catch (Exception e) { throw new InvalidKeySpecException(e); }
    }
    throw new InvalidKeySpecException("Must use RSAPrivateCrtKeySpec 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 RSAPublicKey && X509EncodedKeySpec.class.isAssignableFrom(keySpec))
    {
      return SystemProvider.KeyFactory.getInstance("RSA").getKeySpec(key, keySpec);
    }

    if (key instanceof RSAPublicKey && RSAPublicKeySpec.class.isAssignableFrom(keySpec))
    {
        return (T) new RSAPublicKeySpec(((RSAPublicKey)key).getModulus(), ((RSAPublicKey)key).getPublicExponent());
    }

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

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




© 2015 - 2024 Weber Informatics LLC | Privacy Policy