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

common.crypto.SPE 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.common.crypto;


// Size preserving encryption
public class SPE
{

  static private final int SPE_NONE = 0;
  static private final int SPE_BIT = 1;
  static private final int SPE_FEISTEL = 2;
  static private final int SPE_XTS = 3;


  static private int getMode(int inSize, int bits)
  {
    if (bits==0) bits = inSize*8;

    if (bits == 1) return SPE_BIT;

    if (inSize<=16) // use_festel
    {
      if ((bits & 1)!=0) return SPE_NONE;
      return SPE_FEISTEL;
    }

    if ((bits & 7)!=0) return SPE_NONE;
    return SPE_XTS;
  }


  public static byte[] encrypt(byte[] key, byte[] in, int bits)
  {
    if (bits<=0) bits = in.length*8;
    int mode = getMode(in.length, bits);
    if (mode==SPE_NONE) throw new IllegalArgumentException("Illegal data size for SPE");

    if (mode==SPE_BIT)
    {
      byte[] out = new byte[1];
      out[0] = (byte)((in[0] ^ key[0]) & 1);
      return out;
    }

    if (mode==SPE_FEISTEL)
    {
      byte[] out = new byte[in.length];
      FPE.aesFeistelEncrypt(new AES(key), in, out, bits);
      return out;
    }

    // xts
    return AES.XTS.encrypt(key, in);
  }

  public static byte[] decrypt(byte[] key, byte[] in, int bits)
  {
    if (bits<=0) bits = in.length*8;
    int mode = getMode(in.length, bits);
    if (mode==SPE_NONE) throw new IllegalArgumentException("Illegal data size for SPE");

    if (mode==SPE_BIT)
    {
      byte[] out = new byte[1];
      out[0] = (byte)((in[0] ^ key[0]) & 1);
      return out;
    }

    if (mode==SPE_FEISTEL)
    {
      byte[] out = new byte[in.length];
      FPE.aesFeistelDecrypt(new AES(key), in, out, bits);
      return out;
    }

    // xts
    return AES.XTS.decrypt(key, in);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy