package com.test.framework.utils;
import java.util.Random;
public class TIMPWDOperation
{
/*
* 解密
*/
public static String decrypt(String str)
{
byte b[] = hex2byte(str);
int len = b.length;
b[len - 1] = (byte)(b[len - 1] ^ 0xc);
b[len - 2] = (byte)(b[len - 2] ^ b[len - 1]);
int index = b[len - 1] - b[len - 2];
len = len - index - 2;
for(int i = b.length - 3; i >= len; i--)
b[i] = (byte)(b[i] ^ b[i + 1]);
byte b2[] = new byte[len];
int i = 0;
for(int j = len; i < len; j++)
{
if(j == b.length - 2)
j = len;
b2[i] = (byte)(b[i] ^ b[j]);
i++;
}
return new String(b2);
}
/*
* 加密
*/
public static String encrypt(String str)
{
Random r = new Random();
int len = r.nextInt(5) + 4;
byte b[] = new byte[len + 2];
for(int i = 0; i < len + 1; i++)
{
b[i] = (byte)(r.nextInt(246) - 128);
if(i == b.length - 2)
b[i + 1] = (byte)(b[i] + len);
}
byte b1[] = str.getBytes();
int i = 0;
for(int j = 0; i < b1.length; j++)
{
if(j >= len)
j = 0;
b1[i] = (byte)(b1[i] ^ b[j]);
i++;
}
for(i = 1; i < b.length; i++)
b[i - 1] = (byte)(b[i - 1] ^ b[i]);
b[b.length - 1] = (byte)(b[b.length - 1] ^ 0xc);
return byte2hex(b1) + byte2hex(b);
}
private static String byte2hex(byte b[])
{
String hs = "";
String stmp = "";
for(int n = 0; n < b.length; n++)
{
stmp = Integer.toHexString(b[n] & 0xff);
if(stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
}
return hs.toUpperCase();
}
private static byte[] hex2byte(String str)
{
StringBuffer sb = new StringBuffer(str);
String temp[] = new String[sb.length() / 2];
for(int i = 0; i < temp.length; i++)
temp[i] = sb.substring(2 * i, 2 * i + 2);
byte rlt[] = new byte[temp.length];
for(int i = 0; i < temp.length; i++)
{
String parseStr = temp[i];
int value1 = Integer.parseInt(parseStr, 16);
rlt[i] = (new Integer(value1)).byteValue();
}
return rlt;
}
public static void main(String[] args)
{
TIMPWDOperation pp=new TIMPWDOperation();
//System.out.println(pp.decrypt("1467EC73101323E633C4CB2DB1058B"));
// String pwd="123456";
// String jiam = pp.encrypt(pwd);
// String jiam2 = pp.encrypt(pwd);
// System.out.println(jiam);
// System.out.println(jiam2);
// String jiem = pp.decrypt(jiam);
// String jiem2 = pp.decrypt(jiam2);
// System.out.println(jiem);
// System.out.println(jiem2);
String b = "F0FAC13B6FF7093AFD555C0D07";
String c = pp.decrypt(b);
System.out.println(c);
}
}