64 lines
2.1 KiB
Java
64 lines
2.1 KiB
Java
package run.webup.platform;
|
||
|
||
import java.nio.charset.StandardCharsets;
|
||
import java.security.SecureRandom;
|
||
import java.util.*;
|
||
import javax.crypto.Cipher;
|
||
import javax.crypto.spec.*;
|
||
import org.springframework.beans.factory.annotation.Value;
|
||
import org.springframework.stereotype.Component;
|
||
|
||
@Component
|
||
public class SecretVault {
|
||
private final String configured;
|
||
|
||
public SecretVault(@Value("${app.encryption-key:}") String key) {
|
||
configured = key;
|
||
}
|
||
|
||
private SecretKeySpec key() {
|
||
try {
|
||
byte[] bytes = Base64.getDecoder().decode(configured);
|
||
if (bytes.length == 32) return new SecretKeySpec(bytes, "AES");
|
||
} catch (IllegalArgumentException ignored) {
|
||
}
|
||
throw new ApiError.Failure(503, "尚未配置有效的 APP_ENCRYPTION_KEY(Base64 编码的 32 字节密钥)");
|
||
}
|
||
|
||
public String encrypt(String text) {
|
||
try {
|
||
byte[] iv = new byte[12];
|
||
new SecureRandom().nextBytes(iv);
|
||
Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
|
||
c.init(Cipher.ENCRYPT_MODE, key(), new GCMParameterSpec(128, iv));
|
||
c.updateAAD("provider-key:v1".getBytes(StandardCharsets.UTF_8));
|
||
return "v1:"
|
||
+ Base64.getEncoder().encodeToString(iv)
|
||
+ ":"
|
||
+ Base64.getEncoder().encodeToString(c.doFinal(text.getBytes(StandardCharsets.UTF_8)));
|
||
} catch (ApiError.Failure f) {
|
||
throw f;
|
||
} catch (Exception e) {
|
||
throw new ApiError.Failure(503, "凭证加密失败");
|
||
}
|
||
}
|
||
|
||
public String decrypt(String encrypted) {
|
||
try {
|
||
String[] parts = encrypted.split(":");
|
||
if (parts.length != 3 || !parts[0].equals("v1")) throw new IllegalArgumentException();
|
||
Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
|
||
c.init(
|
||
Cipher.DECRYPT_MODE,
|
||
key(),
|
||
new GCMParameterSpec(128, Base64.getDecoder().decode(parts[1])));
|
||
c.updateAAD("provider-key:v1".getBytes(StandardCharsets.UTF_8));
|
||
return new String(c.doFinal(Base64.getDecoder().decode(parts[2])), StandardCharsets.UTF_8);
|
||
} catch (ApiError.Failure f) {
|
||
throw f;
|
||
} catch (Exception e) {
|
||
throw new ApiError.Failure(503, "凭证解密失败,请检查密钥配置");
|
||
}
|
||
}
|
||
}
|