安全与效率优化,引入Redis,包名修改
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
package com.linkerbot.vibemake.common;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
/** 仅用于项目编码;旧的 UUID 编码继续有效。 */
|
||||
public final class ProjectCodes {
|
||||
public static final String ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz";
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
private ProjectCodes() {}
|
||||
|
||||
public static String next() {
|
||||
StringBuilder code = new StringBuilder(12);
|
||||
for (int i = 0; i < 12; i++) code.append(ALPHABET.charAt(RANDOM.nextInt(32)));
|
||||
return code.toString();
|
||||
}
|
||||
|
||||
public static String github(long repositoryId) {
|
||||
if (repositoryId <= 0) throw new IllegalArgumentException("GitHub 仓库 ID 必须为正数");
|
||||
try {
|
||||
byte[] hash =
|
||||
MessageDigest.getInstance("SHA-256")
|
||||
.digest(
|
||||
("github-import:v1:" + repositoryId)
|
||||
.getBytes(StandardCharsets.UTF_8));
|
||||
StringBuilder code = new StringBuilder(12);
|
||||
for (int i = 0; i < 12; i++) {
|
||||
int offset = i * 5;
|
||||
int pair = (hash[offset / 8] & 255) << 8;
|
||||
if (offset / 8 + 1 < hash.length) pair |= hash[offset / 8 + 1] & 255;
|
||||
code.append(ALPHABET.charAt((pair >>> (11 - offset % 8)) & 31));
|
||||
}
|
||||
return code.toString();
|
||||
} catch (NoSuchAlgorithmException error) {
|
||||
throw new IllegalStateException("SHA-256 不可用", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user