tokenization.com.unbound.common.crypto.SPE Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of unbound-java-provider Show documentation
Show all versions of unbound-java-provider Show documentation
This is a collection of JAVA libraries that implement Unbound cryptographic classes for JAVA provider, PKCS11 wrapper, cryptoki, and advapi
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);
}
}