package com.rrtx.services.common.hostenv;

import com.sun.crypto.provider.SunJCE;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class DesUtils
{
  public static final String ENC_PARA = "DES/ECB/PKCS7Padding";
  private static DesUtils des = null;

  public static DesUtils getInstance()
    throws Exception
  {
    if (des == null) {
      try { if (des == null) {
          des = new DesUtils();
          Security.addProvider(new SunJCE());
          Security.addProvider(new BouncyCastleProvider());
        }
      }
      finally
      {
      }

    }

    return des;
  }

  public byte[] encrypt(byte[] bytP, byte[] key, byte[] ivKey) throws Exception {
    return des(bytP, key, ivKey, 1);
  }

  public byte[] decrypt(byte[] bytE, byte[] key, byte[] ivKey) throws Exception {
    return des(bytE, key, ivKey, 2);
  }

  private byte[] des(byte[] bytP, byte[] key, byte[] ivKey, int mode)
    throws Exception
  {
    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding");

    if ((ivKey != null) && (ivKey.length != 0))
    {
      IvParameterSpec iv = new IvParameterSpec(ivKey);

      cipher.init(mode, getKey(key), iv);
    }
    else {
      cipher.init(mode, getKey(key));
    }

    byte[] enc = cipher.doFinal(bytP);

    return enc;
  }

  private SecretKey getKey(byte[] arrBTmp)
    throws Exception
  {
    byte[] arrB = new byte[8];

    for (int i = 0; (i < arrBTmp.length) && (i < arrB.length); ++i) {
      arrB[i] = arrBTmp[i];
    }

    DESKeySpec desKeySpec = new DESKeySpec(arrBTmp);

    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

    SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

    return secretKey;
  }

  private IvParameterSpec getIvKey(byte[] arrBTmp) {
    byte[] arrB = new byte[8];

    int offset = 0;
    if (arrBTmp.length > 8)
      offset = arrBTmp.length - 8;

    int j = 0;
    for (int i = offset; i < arrBTmp.length; ++i) {
      arrB[(j++)] = arrBTmp[i];
    }

    IvParameterSpec iv = new IvParameterSpec(arrB);

    return iv;
  }
}