AESKeyUtils.java 2.71 KB
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);
    }
}