AESKeyUtils.java
2.71 KB
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
package com.huaheng.common.utils;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
/***
* @author tongzonghao
*
*/
public class AESKeyUtils {
public static String generateAESKeyWithTimestamp(int keySize, long expirationTime) throws NoSuchAlgorithmException, NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(keySize);
SecretKey secretKey = keyGenerator.generateKey();
byte[] keyBytes = secretKey.getEncoded();
// 拼接密钥字节数组和时间戳
byte[] combinedBytes = new byte[keyBytes.length + Long.BYTES];
System.arraycopy(keyBytes, 0, combinedBytes, 0, keyBytes.length);
System.arraycopy(longToByteArray(expirationTime), 0, combinedBytes, keyBytes.length, Long.BYTES);
return Base64.getEncoder().encodeToString(combinedBytes);
}
public static boolean isKeyExpired(String keyWithTimestamp) {
byte[] decodedBytes = Base64.getDecoder().decode(keyWithTimestamp);
int keyLength = decodedBytes.length - Long.BYTES;
byte[] timestampBytes = new byte[Long.BYTES];
System.arraycopy(decodedBytes, keyLength, timestampBytes, 0, Long.BYTES);
long expirationTimestamp = byteArrayToLong(timestampBytes);
return System.currentTimeMillis() > expirationTimestamp;
}
private static byte[] longToByteArray(long value) {
byte[] bytes = new byte[Long.BYTES];
for (int i = 0; i < Long.BYTES; i++) {
bytes[i] = (byte) (value >> ((Long.BYTES - 1 - i) * 8));
}
return bytes;
}
private static long byteArrayToLong(byte[] bytes) {
long value = 0;
for (int i = 0; i < Long.BYTES; i++) {
value |= ((long) (bytes[i] & 0xff)) << ((Long.BYTES - 1 - i) * 8);
}
return value;
}
public static long extractTimestampFromAESKey(String keyWithTimestamp) {
byte[] decodedBytes = Base64.getDecoder().decode(keyWithTimestamp);
// 确保解码后的字节数组长度足够
if (decodedBytes.length < Long.BYTES) {
throw new IllegalArgumentException("Invalid key format: not enough bytes for timestamp");
}
int keyLength = decodedBytes.length - Long.BYTES;
// 检查密钥长度是否合理,这里可以根据实际情况调整
if (keyLength <= 0) {
throw new IllegalArgumentException("Invalid key format: incorrect key length");
}
byte[] timestampBytes = new byte[Long.BYTES];
System.arraycopy(decodedBytes, keyLength, timestampBytes, 0, Long.BYTES);
return byteArrayToLong(timestampBytes);
}
}