package com.test;
import java.io.UnsupportedEncodingException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class DESUtil {
/**
* 加密以byte[]明文输入,byte[]密文输出
*
* @param byteS
* @return
*/
public static byte[] getEncCode( byte[] key,byte[] byteS) {
byte[] byteFina = null;
Cipher cipher;
try {
cipher = Cipher.getInstance("DES/ECB/Nopadding");
DESKeySpec desKey = new DESKeySpec(key);
//创建一个密匙工厂,然后用它把DESKeySpec转换成
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(desKey);
cipher.init(Cipher.ENCRYPT_MODE, securekey);
byteFina = cipher.doFinal(byteS);
} catch (Exception e) {
throw new RuntimeException(
"Error initializing SqlMap class. Cause: " + e);
} finally {
cipher = null;
}
return byteFina;
}
/**
* 解密以byte[]密文输入,以byte[]明文输出
*
* @param byteD
* @return
*/
public static byte[] getDesCode(byte[] key,byte[] byteD) {
Cipher cipher;
byte[] byteFina = null;
try {
cipher = Cipher.getInstance("DES/ECB/Nopadding");
DESKeySpec desKey = new DESKeySpec(key);
//创建一个密匙工厂,然后用它把DESKeySpec转换成
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(desKey);
cipher.init(Cipher.DECRYPT_MODE, securekey);
byteFina = cipher.doFinal(byteD);
} catch (Exception e) {
throw new RuntimeException( e);
} finally {
cipher = null;
}
return byteFina;
}
public static String bytes2HexString(byte[] b) {
StringBuffer returnValue = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
returnValue.append(hex.toUpperCase());
}
return "" + returnValue.toString() + "";
}
public static byte[] hexStr2ByteArray(String hexString) {
hexString = hexString.toLowerCase();
final byte[] byteArray = new byte[hexString.length() / 2];
int k = 0;
for (int i = 0; i < byteArray.length; i++) {
byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);
byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);
byteArray[i] = (byte) (high << 4 | low);
k += 2;
}
return byteArray;
}
//16进制加密,返回16进制数
public static String hexEnDes(String hexKey,String hexData){
byte[] encCode = getEncCode(hexStr2ByteArray(hexKey), hexStr2ByteArray(hexData));
return bytes2HexString(encCode);
}
//16进制加密,返回16进制数
public static byte[] EnDes(byte[] hexKey, byte[] hexData) {
byte[] encCode = getEncCode(hexKey, hexData );
return encCode;
}
//异或
public static byte[] xor(byte[] dest, byte[] source, int size) {
int i;
byte[] a;
byte[] b;
a = dest;
b = source;
for (i = 0; i < size; i++)
a[i] ^= b[i];
dest = a;
return dest;
}
//生成MAC值
public static String GenMac(byte[] hexKey,byte[] sData){
byte[] cbuf= new byte[8+1];
byte[] dbuf= new byte[8];
int i=0, j=0;
int datalen;
byte[] smac= new byte[8];
System.out.println("工作密钥:"+bytes2HexString(hexKey) );
System.out.println("MABBUF:"+sData);
if(sData.length%8 !=0 )
datalen=8-sData.length%8;
else
datalen=0;
byte[] mabbuf= new byte[sData.length+datalen];
for(i=0; i<sData.length; i++ )
mabbuf[i]=sData[i];
System.out.println("datalen:"+datalen+", i:"+i+", j:"+j);
if( datalen != 0 )
for(j=0; j<datalen; j++ )
{
mabbuf[i+j]=' ';
}
System.out.println("新MABBUF"+ mabbuf +" 长度:"+mabbuf.length);
for(i=0; i<mabbuf.length; )
{
for(j=0; j<8; j++)
dbuf[j]=mabbuf[i+j];
i=i+8;
System.out.println("截取数据:"+bytes2HexString(dbuf));
if(i==8)
dbuf=DESUtil.xor( dbuf ,cbuf, 8);
else
dbuf=DESUtil.xor( dbuf ,smac, 8);
System.out.println("异或结果:"+bytes2HexString(dbuf));
smac=DESUtil.EnDes(hexKey, dbuf);
System.out.println("加密结果:"+bytes2HexString(smac));
}
System.out.println("生成的MAC值:"+bytes2HexString(smac));
return bytes2HexString(smac);
}
public static String toHexString(byte[] b) {
String str = "";
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
System.out.print(hex.toUpperCase());
}
return str;
}
public static void printHexString(String hint, byte[] b) {
System.out.print(hint);
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
System.out.print(hex.toUpperCase() + " ");
}
System.out.println("");
}
public static void main(String[] args) throws UnsupportedEncodingException {
String Zmkey = "1111111111111111"; /*主密钥*/
String mwkey = "06B73E606452153C"; /*工作密钥密文*/
/*获取工作密钥明文*/
String key = bytes2HexString(getDesCode(hexStr2ByteArray(Zmkey), hexStr2ByteArray(mwkey) ));
String data = "9882 20140823175518 2000056000 6212960101000654250 370113198906033265测试 00000000000000000000000023000029 9999 ";
byte[] hexdata=data.getBytes( "gbk");
/*生成MAC必须用工作密钥明文*/
System.out.println( GenMac( hexStr2ByteArray(key), hexdata) );
}
}
public class EncryDes {
/* 加密类 */
protected Cipher ecipher;
/* 接密类 */
protected Cipher dcipher;
public EncryDes() {
try {
// Create the key,"emosdnah"为随即初始化密文
String passPhrase = "emosdnah";
/* 生成秘钥 */
KeySpec keySpec = new DESKeySpec(passPhrase.getBytes());
SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(
keySpec);
// SecretKeySpec key = new
// SecretKeySpec(passPhrase.getBytes(),"DES");
/* 初始化加解密实例 */
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameter to the ciphers
// AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt,
// iterationCount);
// Create the ciphers
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 对字符串加密
*
* @param source
* String 要加密的字符串
* @return byte[] 已加密的字节
*/
public byte[] encrypt(String source) {
try {
// Encode the string into bytes using utf-8
// byte[] utf8 = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Encrypt
byte[] enc = ecipher.doFinal(source.getBytes());
// Encode bytes to base64 to get a string
// return new sun.misc.BASE64Encoder().encode(enc);
return enc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 对字节数组解密
*
* @param buf
* byte[]
* @return String
*/
public String decrypt(byte[] buf) {
try {
// Decode base64 to get bytes
// byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(buf);
// Decode using utf-8
// return new String(utf8, "UTF8");
return new String(utf8);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
// } catch (UnsupportedEncodingException e) {
}
return null;
}
/**
* 专用密码加密
*
* @param password
* String
* @return String
*/
public String getEncPass(String password) {
byte[] dst = encrypt(password + " ");// 密码补足十二位
String dstStr = "";
for (int i = 0; i < dst.length && i < 12; i++) {// 密文只取前64位
int cTmp = (int) dst[i] & 0xff;
String hexStr = Integer.toHexString(cTmp);
while (hexStr.length() < 2) {
hexStr = "0" + hexStr;
}
dstStr += hexStr;
}
return dstStr.toUpperCase();
}
public static void main(String []args){
EncryDes des = new EncryDes();
System.out.println(des.getEncPass("1234567890123"));
}
}