leutu
2024-06-03 3ef35e6cd16bbfa206b26bb3271eac40ad020bcb
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
72
73
74
75
package com.fastbee.common.utils;
 
import com.fastbee.common.utils.uuid.IdUtils;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.Validate;
 
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
 
@NoArgsConstructor
public class DigestUtils {
    private static SecureRandom random = new SecureRandom();
    private static IdUtils idUtils = new IdUtils(0,0);
 
    public static String getId(){
        return String.valueOf(Math.abs(random.nextLong()));
    }
 
    public static String nextId(){
        return String.valueOf(idUtils.nextId());
    }
 
 
    public static byte[] genSalt(int numBytes) {
        Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", (long)numBytes);
        byte[] bytes = new byte[numBytes];
        random.nextBytes(bytes);
        return bytes;
    }
 
    public static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);
            if(salt != null) {
                digest.update(salt);
            }
 
            byte[] result = digest.digest(input);
 
            for(int i = 1; i < iterations; ++i) {
                digest.reset();
                result = digest.digest(result);
            }
 
            return result;
        } catch (GeneralSecurityException var7) {
            throw ExceptionUtils.unchecked(var7);
        }
    }
 
    public static byte[] digest(InputStream input, String algorithm) throws IOException {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            int bufferLength = 8192;
            byte[] buffer = new byte[bufferLength];
 
            for(int read = input.read(buffer, 0, bufferLength); read > -1; read = input.read(buffer, 0, bufferLength)) {
                messageDigest.update(buffer, 0, read);
            }
 
            return messageDigest.digest();
        } catch (GeneralSecurityException var6) {
            throw ExceptionUtils.unchecked(var6);
        }
    }
 
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(nextId());
        }
    }
}