package com.xfestudio.xfeservermanager.infra.security;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.EnumSet;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/** Loads or creates the local AES key used to encrypt TOTP seeds at rest. */
public final class MasterKeyFile {
private static final SecureRandom RANDOM = new SecureRandom();
private MasterKeyFile() {}
public static synchronized SecretKey loadOrCreate(Path file) throws IOException {
Path absolute = file.toAbsolutePath().normalize();
Path parent = absolute.getParent();
if (parent != null) {
Files.createDirectories(parent);
}
if (Files.exists(absolute)) {
return read(absolute);
}
byte[] raw = new byte[32];
RANDOM.nextBytes(raw);
byte[] encoded = Base64.getUrlEncoder().withoutPadding().encode(raw);
try {
createOwnerOnly(absolute, encoded);
return new SecretKeySpec(raw, "AES");
} catch (FileAlreadyExistsException raced) {
return read(absolute);
} finally {
java.util.Arrays.fill(raw, (byte) 0);
java.util.Arrays.fill(encoded, (byte) 0);
}
}
private static SecretKey read(Path file) throws IOException {
if (!Files.isRegularFile(file, java.nio.file.LinkOption.NOFOLLOW_LINKS)
|| Files.size(file) > 128) {
throw new IOException("master key must be a small regular file, not a symbolic link");
}
byte[] decoded;
try {
decoded = Base64.getUrlDecoder().decode(Files.readString(file).trim());
} catch (IllegalArgumentException malformed) {
throw new IOException("invalid master key encoding", malformed);
}
try {
if (decoded.length != 32) {
throw new IOException("invalid master key length");
}
return new SecretKeySpec(decoded, "AES");
} finally {
java.util.Arrays.fill(decoded, (byte) 0);
}
}
private static void createOwnerOnly(Path file, byte[] encoded) throws IOException {
var permissions = PosixFilePermissions.asFileAttribute(
EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE));
FileChannel channel;
try {
channel = FileChannel.open(
file,
EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE),
permissions);
} catch (UnsupportedOperationException ignored) {
channel = FileChannel.open(file, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
}
try (FileChannel lockedChannel = channel) {
ByteBuffer buffer = ByteBuffer.wrap(encoded);
while (buffer.hasRemaining()) {
lockedChannel.write(buffer);
}
lockedChannel.force(true);
}
}
}
package com.xfestudio.xfeservermanager.infra.security;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.EnumSet;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/** Loads or creates the local AES key used to encrypt TOTP seeds at rest. */
public final class MasterKeyFile {
private static final SecureRandom RANDOM = new SecureRandom();
private MasterKeyFile() {}
public static synchronized SecretKey loadOrCreate(Path file) throws IOException {
Path absolute = file.toAbsolutePath().normalize();
Path parent = absolute.getParent();
if (parent != null) {
Files.createDirectories(parent);
}
if (Files.exists(absolute)) {
return read(absolute);
}
byte[] raw = new byte[32];
RANDOM.nextBytes(raw);
byte[] encoded = Base64.getUrlEncoder().withoutPadding().encode(raw);
try {
createOwnerOnly(absolute, encoded);
return new SecretKeySpec(raw, "AES");
} catch (FileAlreadyExistsException raced) {
return read(absolute);
} finally {
java.util.Arrays.fill(raw, (byte) 0);
java.util.Arrays.fill(encoded, (byte) 0);
}
}
private static SecretKey read(Path file) throws IOException {
if (!Files.isRegularFile(file, java.nio.file.LinkOption.NOFOLLOW_LINKS)
|| Files.size(file) > 128) {
throw new IOException("master key must be a small regular file, not a symbolic link");
}
byte[] decoded;
try {
decoded = Base64.getUrlDecoder().decode(Files.readString(file).trim());
} catch (IllegalArgumentException malformed) {
throw new IOException("invalid master key encoding", malformed);
}
try {
if (decoded.length != 32) {
throw new IOException("invalid master key length");
}
return new SecretKeySpec(decoded, "AES");
} finally {
java.util.Arrays.fill(decoded, (byte) 0);
}
}
private static void createOwnerOnly(Path file, byte[] encoded) throws IOException {
var permissions = PosixFilePermissions.asFileAttribute(
EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE));
FileChannel channel;
try {
channel = FileChannel.open(
file,
EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE),
permissions);
} catch (UnsupportedOperationException ignored) {
channel = FileChannel.open(file, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
}
try (FileChannel lockedChannel = channel) {
ByteBuffer buffer = ByteBuffer.wrap(encoded);
while (buffer.hasRemaining()) {
lockedChannel.write(buffer);
}
lockedChannel.force(true);
}
}
}