using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace GameLauncher.Services.Codecs.Es3
{
///
/// "どの段階でパスワードが判明したか" を表す解決手段の種別。
///
public enum Es3PasswordSource
{
/// 学習キャッシュ(過去に解決済みのパスワード)から復元。
LearnedCache,
/// 呼び出し元が明示指定したパスワード。
Explicit,
/// ゲーム内のマネージドアセンブリ(Assembly-CSharp.dll 等)の文字列リテラルから抽出。
GameBinaryStrings,
/// ゲーム内バイナリ(IL2CPP の GameAssembly.dll / global-metadata.dat)から抽出。
GameIl2CppMetadata,
/// ユーザー辞書ファイル/既定の候補リストからの探索。
Dictionary,
/// 平文のまま(暗号化されていない)。
PlainText
}
///
/// ES3 パスワード解決の結果。 が false の場合は に理由が入ります。
///
public sealed class Es3PasswordResolution
{
/// 解決に成功したか。
public bool Success { get; init; }
/// 解決したパスワード(平文・暗号化なしの場合は空文字)。
public string Password { get; init; } = string.Empty;
/// 解決手段の種別。
public Es3PasswordSource Source { get; init; }
/// 試行した候補数。
public int TriedCandidates { get; init; }
/// 診断用のメッセージ一覧(失敗理由・各段階の結果)。
public IReadOnlyList Diagnostics { get; init; } = [];
/// 失敗結果を生成します。
public static Es3PasswordResolution Fail(List diagnostics, int tried)
=> new() { Success = false, Diagnostics = diagnostics, TriedCandidates = tried };
/// 成功結果を生成します。
public static Es3PasswordResolution Ok(string password, Es3PasswordSource source, int tried)
=> new() { Success = true, Password = password, Source = source, TriedCandidates = tried };
}
///
/// ES3 (Easy Save 3) の暗号化セーブデータからパスワードを多段フォールバックで特定する汎用リゾルバ。
///
/// 解決順序:
/// 1. 学習キャッシュ()
/// 2. 呼び出し元の明示指定
/// 3. ゲームのマネージドアセンブリ文字列リテラル抽出(Mono)
/// 4. 既定候補 + ユーザー辞書による探索
///
/// すべての候補は実際に AES 復号して妥当性を検証し、成功したものだけを採用します。
/// これにより「誤ったパスワードで復号して壊れたデータを書く」事故を防止します。
///
public sealed class Es3PasswordResolver
{
/// ES3 が AES 暗号化時にファイル先頭へ埋め込む IV の長さ(バイト)。
public const int AesIvLength = 16;
/// 復号結果が「ES3 の平文 JSON」らしいかを判定する際の最小文字数。
private const int MinimumPlainTextLength = 2;
private readonly Es3PasswordStore _store;
///
/// 既定のストアを用いて を初期化します。
///
public Es3PasswordResolver()
: this(Es3PasswordStore.Instance)
{
}
///
/// 任意のストアを指定して を初期化します(テスト用途を含む)。
///
/// 学習済みパスワードの永続ストア
public Es3PasswordResolver(Es3PasswordStore store)
{
this._store = store ?? throw new ArgumentNullException(nameof(store));
}
///
/// 既定のシングルトンインスタンス。
///
public static Es3PasswordResolver Instance { get; } = new();
///
/// ES3 のファイルが暗号化されているかどうかを統計的に判定します。
/// 平文 JSON / Gzip はもちろん「暗号化されていない」と判定します。
///
/// ファイル全体のバイト列
/// 暗号化されている可能性が高い場合 true
public static bool LooksEncrypted(byte[] bytes)
{
if (bytes == null || bytes.Length < AesIvLength * 2)
{
return false;
}
// 平文 JSON はそのまま読める
if (IsLikelyJson(bytes))
{
return false;
}
// Gzip マジック
if (bytes[0] == 0x1F && bytes[1] == 0x8B)
{
return false;
}
// AES ブロック境界に一致し、かつ高エントロピーなら暗号化とみなす
if (bytes.Length % AesIvLength != 0)
{
return false;
}
return CalculateEntropy(bytes) >= 7.5;
}
///
/// パスワードを多段フォールバックで解決します。
///
/// 対象の .es3 ファイルの絶対パス
/// ゲームのルートディレクトリ(文字列抽出元の探索に使用)
/// 学習キャッシュのキー(通常はゲームのルートディレクトリ)
/// 呼び出し元が既に知っているパスワード(任意)
/// 追加候補を列挙したテキストファイルのパス(任意)
/// 解決結果
public Es3PasswordResolution Resolve(
string saveFilePath,
string? gameRootDirectory = null,
string? gameKey = null,
string? explicitPassword = null,
string? userDictionaryPath = null)
{
var diagnostics = new List();
int tried = 0;
byte[] fileBytes;
try
{
fileBytes = File.ReadAllBytes(saveFilePath);
}
catch (Exception ex)
{
diagnostics.Add($"セーブファイルを読み込めません: {ex.Message}");
return Es3PasswordResolution.Fail(diagnostics, tried);
}
if (fileBytes.Length == 0)
{
diagnostics.Add("セーブファイルが空です。");
return Es3PasswordResolution.Fail(diagnostics, tried);
}
// 暗号化されていない場合はパスワード不要
if (!LooksEncrypted(fileBytes))
{
diagnostics.Add("暗号化は検出されませんでした(平文または Gzip)。");
return Es3PasswordResolution.Ok(string.Empty, Es3PasswordSource.PlainText, tried);
}
diagnostics.Add($"暗号化を検出しました({fileBytes.Length} bytes / AES-128-CBC 相当)。");
// ---- 段階 1: 学習キャッシュ ----
var cacheKey = this.BuildCacheKey(gameKey, saveFilePath);
if (!string.IsNullOrEmpty(cacheKey))
{
var learned = this._store.TryGet(cacheKey);
if (!string.IsNullOrEmpty(learned))
{
tried++;
if (this.VerifyPassword(fileBytes, learned, out _))
{
diagnostics.Add("学習キャッシュのパスワードで復号に成功しました。");
return Es3PasswordResolution.Ok(learned, Es3PasswordSource.LearnedCache, tried);
}
diagnostics.Add("学習キャッシュのパスワードは無効でした(破棄します)。");
this._store.Remove(cacheKey);
}
}
// ---- 段階 2: 明示指定 ----
if (!string.IsNullOrEmpty(explicitPassword))
{
tried++;
if (this.VerifyPassword(fileBytes, explicitPassword, out _))
{
diagnostics.Add("指定されたパスワードで復号に成功しました。");
this.Remember(cacheKey, explicitPassword);
return Es3PasswordResolution.Ok(explicitPassword, Es3PasswordSource.Explicit, tried);
}
diagnostics.Add("指定されたパスワードでは復号できませんでした。");
}
// ---- 段階 3: ゲームバイナリの文字列リテラル抽出 ----
if (!string.IsNullOrEmpty(gameRootDirectory) && Directory.Exists(gameRootDirectory))
{
var extracted = Es3PasswordExtractor.ExtractCandidates(gameRootDirectory, diagnostics);
foreach (var candidate in extracted)
{
tried++;
if (this.VerifyPassword(fileBytes, candidate, out _))
{
diagnostics.Add($"ゲームバイナリから抽出した候補で復号に成功しました(候補: {Mask(candidate)})。");
this.Remember(cacheKey, candidate);
return Es3PasswordResolution.Ok(candidate, Es3PasswordSource.GameBinaryStrings, tried);
}
}
if (extracted.Count == 0)
{
diagnostics.Add("ゲームバイナリから有効なパスワード候補を抽出できませんでした。");
}
}
// ---- 段階 4: 既定候補 + ユーザー辞書 ----
foreach (var candidate in this.EnumerateDictionaryCandidates(userDictionaryPath, diagnostics))
{
tried++;
if (this.VerifyPassword(fileBytes, candidate, out _))
{
diagnostics.Add($"辞書探索で復号に成功しました(候補: {Mask(candidate)})。");
this.Remember(cacheKey, candidate);
return Es3PasswordResolution.Ok(candidate, Es3PasswordSource.Dictionary, tried);
}
}
diagnostics.Add($"すべての段階で復号に失敗しました(試行候補数: {tried})。パスワードを手動で入力してください。");
return Es3PasswordResolution.Fail(diagnostics, tried);
}
///
/// 指定パスワードで ES3 ファイルを復号し、平文 JSON 文字列を取得します。
///
/// ファイル全体のバイト列
/// パスワード
/// 復号された平文 JSON
/// 復号に成功した場合 true
public bool VerifyPassword(byte[] fileBytes, string password, out string plainText)
{
plainText = string.Empty;
var plain = TryDecrypt(fileBytes, password);
if (plain == null)
{
return false;
}
plainText = plain;
return true;
}
///
/// ES3 の AES-128-CBC 形式で復号を試みます。
/// ファイル先頭 16 バイトを IV、残りを暗号文として扱い、鍵はパスワード UTF-8 の先頭 16 バイトをゼロ埋めします。
///
/// ファイル全体のバイト列
/// パスワード
/// 復号された平文 JSON。失敗時は null
public static string? TryDecrypt(byte[] fileBytes, string password)
{
if (fileBytes == null || fileBytes.Length <= AesIvLength)
{
return null;
}
try
{
var iv = new byte[AesIvLength];
Array.Copy(fileBytes, 0, iv, 0, AesIvLength);
var cipher = new byte[fileBytes.Length - AesIvLength];
Array.Copy(fileBytes, AesIvLength, cipher, 0, cipher.Length);
using var aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = DeriveKey(password);
aes.IV = iv;
using var decryptor = aes.CreateDecryptor();
var plain = decryptor.TransformFinalBlock(cipher, 0, cipher.Length);
var text = Encoding.UTF8.GetString(plain);
return IsPlausiblePlainText(text) ? text : null;
}
catch
{
return null;
}
}
///
/// 平文バイト列を ES3 の AES-128-CBC 形式で暗号化します(IV を先頭に付与)。
///
/// 平文バイト列
/// パスワード
/// IV + 暗号文のバイト列
public static byte[] Encrypt(byte[] plainBytes, string password)
{
using var aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = DeriveKey(password);
aes.GenerateIV();
using var encryptor = aes.CreateEncryptor();
var cipher = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
var result = new byte[aes.IV.Length + cipher.Length];
Array.Copy(aes.IV, 0, result, 0, aes.IV.Length);
Array.Copy(cipher, 0, result, aes.IV.Length, cipher.Length);
return result;
}
///
/// パスワード文字列から AES-128 用の 16 バイト鍵を導出します。
///
/// パスワード
/// 16 バイトの鍵
private static byte[] DeriveKey(string password)
{
var raw = Encoding.UTF8.GetBytes(password ?? string.Empty);
var key = new byte[16];
Array.Copy(raw, key, Math.Min(raw.Length, key.Length));
return key;
}
///
/// 復号結果が ES3 の平文として妥当かを判定します。
///
/// 復号された文字列
/// 妥当な場合 true
private static bool IsPlausiblePlainText(string text)
{
if (string.IsNullOrWhiteSpace(text) || text.Length < MinimumPlainTextLength)
{
return false;
}
var trimmed = text.TrimStart();
if (trimmed.StartsWith('{') || trimmed.StartsWith('['))
{
return true;
}
// ES3 の内部シリアライズ形式は "__type" を必ず含む
return text.Contains("__type", StringComparison.Ordinal);
}
///
/// バイト列が平文 JSON かどうかを判定します。
///
/// 対象バイト列
/// 平文 JSON と判断できる場合 true
private static bool IsLikelyJson(byte[] bytes)
{
try
{
int length = Math.Min(bytes.Length, 64);
var head = Encoding.UTF8.GetString(bytes, 0, length).TrimStart();
return head.StartsWith('{') || head.StartsWith('[');
}
catch
{
return false;
}
}
///
/// バイト列のシャノンエントロピー(bits/byte)を算出します。
///
/// 対象バイト列
/// エントロピー値
private static double CalculateEntropy(byte[] bytes)
{
var frequency = new int[256];
foreach (var b in bytes)
{
frequency[b]++;
}
double entropy = 0.0;
foreach (var count in frequency)
{
if (count == 0)
{
continue;
}
double p = (double)count / bytes.Length;
entropy -= p * Math.Log2(p);
}
return entropy;
}
///
/// 学習キャッシュ用のキーを生成します。
///
/// ゲーム識別キー
/// セーブファイルパス
/// キャッシュキー
private string BuildCacheKey(string? gameKey, string saveFilePath)
{
var key = !string.IsNullOrWhiteSpace(gameKey)
? gameKey!
: Path.GetDirectoryName(saveFilePath) ?? string.Empty;
return key.Trim();
}
///
/// 解決済みパスワードを学習キャッシュへ保存します。
///
/// キャッシュキー
/// パスワード
private void Remember(string? cacheKey, string password)
{
if (string.IsNullOrEmpty(cacheKey))
{
return;
}
this._store.Set(cacheKey, password);
}
///
/// 辞書段階で試行する候補列挙子を返します(既定候補 → ユーザー辞書の順)。
///
/// ユーザー辞書ファイルのパス
/// 診断メッセージの追加先
/// 候補の列挙
private IEnumerable EnumerateDictionaryCandidates(string? userDictionaryPath, List diagnostics)
{
var seen = new HashSet(StringComparer.Ordinal);
foreach (var candidate in GetBuiltInCandidates())
{
if (seen.Add(candidate))
{
yield return candidate;
}
}
if (string.IsNullOrWhiteSpace(userDictionaryPath))
{
yield break;
}
if (!File.Exists(userDictionaryPath))
{
diagnostics.Add($"ユーザー辞書が見つかりません: {userDictionaryPath}");
yield break;
}
string[] lines;
try
{
lines = File.ReadAllLines(userDictionaryPath, Encoding.UTF8);
}
catch (Exception ex)
{
diagnostics.Add($"ユーザー辞書の読み込みに失敗しました: {ex.Message}");
yield break;
}
diagnostics.Add($"ユーザー辞書を適用します({lines.Length} 行): {userDictionaryPath}");
foreach (var line in lines)
{
var candidate = line.Trim();
if (candidate.Length == 0 || candidate.StartsWith('#'))
{
continue;
}
if (seen.Add(candidate))
{
yield return candidate;
}
}
}
///
/// Easy Save 3 でよく使われる既定のパスワード候補を返します。
///
/// 既定候補の並び
private static IEnumerable GetBuiltInCandidates()
{
// 空文字(パスワード未設定のまま暗号化されたケース)を最初に試す
yield return string.Empty;
yield return "password";
yield return "Password";
yield return "PASSWORD";
yield return "Moodkie";
yield return "moodkie";
yield return "EasySave";
yield return "easysave";
yield return "EasySave3";
yield return "es3";
yield return "ES3";
yield return "SaveData";
yield return "savedata";
yield return "Save";
yield return "save";
yield return "secret";
yield return "Secret";
yield return "123456";
yield return "1234567890";
yield return "admin";
yield return "test";
yield return "game";
yield return "Game";
}
///
/// 診断ログ用にパスワードをマスクします(先頭 2 文字のみ残す)。
///
/// パスワード
/// マスク済み文字列
private static string Mask(string password)
{
if (string.IsNullOrEmpty(password))
{
return "(空)";
}
if (password.Length <= 2)
{
return new string('*', password.Length);
}
return password[..2] + new string('*', Math.Min(password.Length - 2, 8));
}
}
}