xiaoyong931011
2020-11-30 7ae23e17d8e90dc634f3f86e2eee209cbacaace3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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());
    }
}