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

com.unbound.provider.UBSecretKey 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.KeyParameters;
import com.unbound.common.Log;
import com.unbound.provider.kmip.KMIP;
import com.unbound.provider.kmip.attribute.*;
import com.unbound.provider.kmip.object.SymmetricKey;
import com.unbound.provider.kmip.request.*;
import com.unbound.provider.kmip.response.*;

import javax.crypto.SecretKey;

import java.io.IOException;
import java.security.Key;
import java.security.ProviderException;
import java.security.cert.CertificateException;
import java.security.spec.InvalidKeySpecException;

public class UBSecretKey extends UBObject implements javax.crypto.SecretKey
{
  int kmipAlg;

  UBSecretKey(Partition partition, int kmipAlg)
  {
    super(partition);
    this.kmipAlg = kmipAlg;
  }

  int getKmipAlg() { return kmipAlg; }

  UBSecretKey(Partition partition, long uid, GetAttributesResponse getAttrResp)
  {
    super(partition, uid, getAttrResp);
  }

  static UBSecretKey newSecretKey(KeyParameters keyParameter, Partition partition, String alias, Key key) throws IOException
  {
    if (!(key instanceof SecretKey)) throw new ProviderException("Unsupported key type");
    String alg = key.getAlgorithm();
    int kmipAlg = 0;
    if (alg.equalsIgnoreCase("AES")) kmipAlg = KMIP.CryptographicAlgorithm.AES;
    else if (alg.equalsIgnoreCase("HMAC")) kmipAlg = KMIP.CryptographicAlgorithm.HMAC_SHA256;
    else throw new ProviderException("Unsupported algorithm");

    UBSecretKey secret = new UBSecretKey(partition, kmipAlg);
    secret.register(keyParameter, ((SecretKey)key).getEncoded(), alias);
    return secret;
  }

  static UBSecretKey locate(Partition partition, String alias) throws CertificateException, InvalidKeySpecException, IOException
  {
    long uid = 0;
    Log log = Log.func("UBSecretKey.locate").log("alias", alias).end(); try
    {
      uid = partition.locate(KMIP.ObjectType.SymmetricKey, 0, alias);
      if (uid==0) return null;
      return (UBSecretKey) UBObject.read(partition, uid, false);
    }
    catch (Exception e) { log.failed(e); throw e; } finally { log.leavePrint().logHex("uid", uid).end(); }
  }

  static UBSecretKey read(Partition partition, long uid) throws IOException
  {
    ResponseMessage resp = partition.read(uid, false);
    GetAttributesResponse getAttrResp = (GetAttributesResponse) resp.batch.get(0);
    return new UBSecretKey(partition, uid, getAttrResp);
  }

  private void register(KeyParameters keyParameter, RegisterRequest reqRegister, String alias) throws IOException
  {
    Log log = Log.func("UBSecretKey.register").log("alias", alias).end(); try
    {
      int kmipUsage =
        KMIP.CryptographicUsageMask.MACGenerate |
        KMIP.CryptographicUsageMask.MACVerify;

      if (kmipAlg==KMIP.CryptographicAlgorithm.AES)
      {
        kmipUsage |=
          KMIP.CryptographicUsageMask.Encrypt |
          KMIP.CryptographicUsageMask.Decrypt;
      }

      RequestMessage reqMsg = new RequestMessage();
      reqRegister.template = new TemplateAttribute();

      if (keyParameter!=null)
      {
        kmipUsage = updateKmipKeyUsageMask(keyParameter, kmipUsage, true);
        updateAttrs(keyParameter, reqRegister.template.attrs);
      }

      reqRegister.template.attrs.add(new EnumAttribute(KMIP.Tag.CryptographicAlgorithm, kmipAlg));
      reqRegister.template.attrs.add(new IntAttribute(KMIP.Tag.CryptographicUsageMask, kmipUsage));
      if (alias!=null) reqRegister.template.attrs.add(new Name(alias));

      reqMsg.batch.add(reqRegister);

      ActivateRequest reqActivate = new ActivateRequest();
      reqMsg.batch.add(reqActivate);

      GetAttributesRequest reqGetAttr = new GetAttributesRequest();
      reqMsg.batch.add(reqGetAttr);
      reqGetAttr.names.add("Name");
      reqGetAttr.names.add("Initial Date");

      ResponseMessage respMsg = partition.transmit(reqMsg);

      RegisterResponse respRegister = (RegisterResponse)respMsg.batch.get(0);
      GetAttributesResponse respGetAttr = (GetAttributesResponse)respMsg.batch.get(2);

      uid = strToUid(respRegister.uid);
      name = alias==null ? ((Name)respGetAttr.attrs.get(0)).value : alias;
      initialDate = ((DateAttribute)respGetAttr.attrs.get(1)).value;
    }
    catch (Exception e) { log.failed(e); throw e; } finally { log.leavePrint().logHex("UID", uid).end(); }
  }

  void register(KeyParameters keyParameter, byte[] keyValue, String alias) throws IOException
  {
    Log log = Log.func("UBSecretKey.register").log("bitSize", keyValue.length*8).end(); try
    {
      RegisterRequest reqRegister = new RegisterRequest();
      SymmetricKey symmetricKey = new SymmetricKey();
      symmetricKey.keyBlock.formatType = KMIP.KeyFormatType.Raw;
      symmetricKey.keyBlock.buf = keyValue;
      reqRegister.objectType = KMIP.ObjectType.SymmetricKey;
      reqRegister.object = symmetricKey;
      register(keyParameter, reqRegister, alias);
    }
    catch (Exception e) { log.failed(e); throw e; } finally { log.leavePrint().logHex("UID", uid).end(); }
  }

  void generate(KeyParameters keyParameter, int bitSize) throws IOException
  {
    Log log = Log.func("UBSecretKey.generate").log("bitSize", bitSize).end(); try
    {
      RequestMessage reqMsg = new RequestMessage();

      CreateRequest reqCreate = new CreateRequest();
      reqMsg.batch.add(reqCreate);
      reqCreate.template = new TemplateAttribute();
      reqCreate.objectType = KMIP.ObjectType.SymmetricKey;

      int kmipUsage =
        KMIP.CryptographicUsageMask.MACGenerate |
        KMIP.CryptographicUsageMask.MACVerify;

      if (kmipAlg==KMIP.CryptographicAlgorithm.AES)
      {
        kmipUsage |=
          KMIP.CryptographicUsageMask.Encrypt |
          KMIP.CryptographicUsageMask.Decrypt;
      }

      if (keyParameter!=null)
      {
        kmipUsage = updateKmipKeyUsageMask(keyParameter, kmipUsage, true);
        updateAttrs(keyParameter, reqCreate.template.attrs);
      }

      reqCreate.template.attrs.add(new EnumAttribute(KMIP.Tag.CryptographicAlgorithm, kmipAlg));
      reqCreate.template.attrs.add(new IntAttribute(KMIP.Tag.CryptographicLength, bitSize));
      reqCreate.template.attrs.add(new IntAttribute(KMIP.Tag.CryptographicUsageMask, kmipUsage));

      ActivateRequest reqActivate = new ActivateRequest();
      reqMsg.batch.add(reqActivate);

      GetAttributesRequest reqGetAttr = new GetAttributesRequest();
      reqMsg.batch.add(reqGetAttr);
      reqGetAttr.names.add("Name");
      reqGetAttr.names.add("Initial Date");

      ResponseMessage respMsg = partition.transmit(reqMsg);

      CreateResponse respCreate = (CreateResponse)respMsg.batch.get(0);
      GetAttributesResponse respGetAttr = (GetAttributesResponse)respMsg.batch.get(2);

      uid = strToUid(respCreate.uid);
      name = ((Name)respGetAttr.attrs.get(0)).value;
      initialDate = ((DateAttribute)respGetAttr.attrs.get(1)).value;
    }
    catch (Exception e) { log.failed(e); throw e; } finally { log.leavePrint().logHex("UID", uid).end(); }
  }

  void unwrap(KeyParameters keyParameter, RegisterRequest req, long unwrappingKeyUid, CryptoParams kmipParams, byte[] wrapped) throws IOException
  {
    Log log = Log.func("UBSecretKey.unwrap").end(); try
    {
      SymmetricKey managedObject = new SymmetricKey();
      req.objectType = KMIP.ObjectType.SymmetricKey;
      req.object = managedObject;
      managedObject.keyBlock.buf = wrapped;
      managedObject.keyBlock.formatType = KMIP.KeyFormatType.Raw;
      managedObject.keyBlock.keyWrap = new KeyWrappingData();
      managedObject.keyBlock.keyWrap.encKey = new KeyWrappingInfo();
      managedObject.keyBlock.keyWrap.encKey.uid = uidToStr(unwrappingKeyUid);
      managedObject.keyBlock.keyWrap.encKey.params = kmipParams;

      register(keyParameter, req, null);
    }
    catch (Exception e) { log.failed(e); throw e; } finally { log.leavePrint().logHex("UID", uid).end(); }
  }
  // ----------------------- interface -----------------------------

  @Override
  int kmipObjectType() { return KMIP.ObjectType.SymmetricKey; }

  @Override
  public String getFormat() { return null; }

  @Override
  public byte[] getEncoded() { throw new ProviderException("Function not supported"); }

  @Override
  public String getAlgorithm()
  {
    if (kmipAlg==KMIP.CryptographicAlgorithm.AES)  return "AES";
    return "Hmac";
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy