package com.xcong.excoin.utils;
|
|
|
import javax.crypto.Cipher;
|
import javax.crypto.KeyGenerator;
|
import javax.crypto.NoSuchPaddingException;
|
import javax.crypto.SecretKey;
|
import javax.crypto.spec.SecretKeySpec;
|
import java.util.Formatter;
|
|
|
public class DESUtil {
|
|
/*
|
* 生成密钥
|
*/
|
public static byte[] initKey() throws Exception{
|
KeyGenerator keyGen = KeyGenerator.getInstance("DES");
|
keyGen.init(56);
|
SecretKey secretKey = keyGen.generateKey();
|
return secretKey.getEncoded();
|
}
|
|
|
/*
|
* DES 加密
|
*/
|
public static byte[] encrypt(byte[] data, byte[] key) throws Exception{
|
SecretKey secretKey = new SecretKeySpec(key, "DES");
|
|
Cipher cipher = Cipher.getInstance("DES");
|
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
|
byte[] cipherBytes = cipher.doFinal(data);
|
return cipherBytes;
|
}
|
|
|
/*
|
* DES 解密
|
*/
|
public static byte[] decrypt(byte[] data, byte[] key) throws Exception{
|
SecretKey secretKey = new SecretKeySpec(key, "DES");
|
|
Cipher cipher = Cipher.getInstance("DES");
|
cipher.init(Cipher.DECRYPT_MODE, secretKey);
|
byte[] plainBytes = cipher.doFinal(data);
|
return plainBytes;
|
}
|
|
public static String byteToHex(final byte[] hash) {
|
Formatter formatter = new Formatter();
|
for (byte b : hash) {
|
formatter.format("%02x", b);
|
}
|
String result = formatter.toString();
|
formatter.close();
|
return result;
|
}
|
//Test
|
public static void main(String[] args) throws Exception {
|
// byte[] desKey = DESUtil.initKey();
|
// String da = UUIDUtil.getRandomID();
|
// System.out.println("DES KEY : " + byteToHex(desKey));
|
// byte[] desResult = DESUtil.encrypt(da.getBytes(), desKey);
|
// System.out.println(da + ">>>DES 加密结果>>>" + byteToHex(desResult));
|
//
|
// byte[] desPlain = DESUtil.decrypt(desResult, desKey);
|
// System.out.println(da+ ">>>DES 解密结果>>>" + new String(desPlain));
|
System.out.println("b68edd21786c4d4816284e2ad6d6291aaf4091cd3a0fc7898f4aa52153d730a32bf17f803a91ffde".length());
|
}
|
}
|