feat(decrypt): 支持酷狗 .kgg 格式

原先的解密依赖 MusicDecrypto.Library,它支持 ncm/qmc/kgm/kgma/kwm,但任何
版本都不支持 .kgg,这类文件会被直接拒绝。

.kgg 不是自包含的:音频用 QMC2 加密,而每个文件的 ekey 并不存放在文件里。
文件里只有偏移 0x48 处的 32 字节音频哈希;对应的 ekey 在酷狗客户端的
KGMusicV3.db(表 ShareFileItems)里,而这个数据库本身也是逐页加密的。

所以必须先读数据库:

  1. 逐页解密 KGMusicV3.db(AES-128-CBC,key/IV 由主密钥和页号派生)
  2. 用文件的音频哈希查出 ekey
  3. 解码 ekey(TC-TEA CBC,含 V2 两段式变体)
  4. 构造 QMC2 解密器(短密钥用映射表,长密钥用 RC4)
  5. 按 1 MB 分块流式解密音频
  6. 读解密后的头 4 个字节判断真实扩展名(fLaC / OggS / 否则 mp3)

实际后果:.kgg 只能在本机解密,因为那条 ekey 记录只有在酷狗客户端下载过
这首歌时才会写入。别人给的 .kgg 解不了。

新增内容:
- Common/MusicDecryption/Kugou/ —— TcTea、EkeyDecoder、Qmc2Cipher、
  KugouEkeyDatabase、KggMusicDecryptor
- IKugouKeyProvider / KugouKeyProvider —— 探测数据库、缓存已解析的密钥表、
  支持手动指定数据库路径
- IMusicDecryptor.ConvertMusicAsync 增加可选 CancellationToken,让大文件真的
  能被中断(桌面端有"停止"按钮)
- 输出先写 .part,校验字节数之后才改名,中途中断不会留下一个看起来完成
  了的残缺文件

注意:
- Microsoft.Data.Sqlite 会传递引入 SQLitePCLRaw.lib.e_sqlite3 2.1.11,该版本
  被 NU1903 / GHSA-2m69-gcr7-jv3q 标记。显式引用
  SQLitePCLRaw.bundle_e_sqlite3 3.0.5 覆盖掉它。
- e_sqlite3.dll 是原生依赖,单文件发布会把它留在 exe 外面,必须随包分发。

酷狗算法移植自 MIT 协议的 kgg-dec 参考实现,因此 THIRD-PARTY-NOTICES.md
带上原始版权与许可声明,每个移植文件头部也标了来源。
This commit is contained in:
aL1CesT committed 2026-11-09 04:27:41 +08:00
1 parent 1c0f8e8d3a
commit 168a8e42f1
12 files changed
+1515 -7

No files matched your search

+3
View File
@@ -41,6 +41,9 @@
<!-- Misc --> <!-- Misc -->
<PackageVersion Include="Ude.NetStandard" Version="1.2.0" /> <PackageVersion Include="Ude.NetStandard" Version="1.2.0" />
<PackageVersion Include="YamlDotNet" Version="16.3.0" /> <PackageVersion Include="YamlDotNet" Version="16.3.0" />
<PackageVersion Include="Microsoft.Data.Sqlite" Version="10.0.1" />
<!-- 显式提升 SQLitePCLRaw 的原生包:Microsoft.Data.Sqlite 10.0.1 默认带下来的 2.1.11 有已知高危漏洞(GHSA-2m69-gcr7-jv3q)。 -->
<PackageVersion Include="SQLitePCLRaw.bundle_e_sqlite3" Version="3.0.5" />
<!-- Avalonia --> <!-- Avalonia -->
<PackageVersion Include="Avalonia" Version="11.2.3" /> <PackageVersion Include="Avalonia" Version="11.2.3" />
<PackageVersion Include="Avalonia.Desktop" Version="11.2.3" /> <PackageVersion Include="Avalonia.Desktop" Version="11.2.3" />
+45
View File
@@ -0,0 +1,45 @@
# Third-Party Notices
This project contains code derived from the following MIT-licensed works.
The MIT licence requires the copyright notice and permission notice to be
included in all copies or substantial portions of the software, so they are
reproduced in full below.
---
## kgg-dec — KuGou `.kgg` decryption reference implementation
Source: <https://github.com/lizipeng0013/kgg-dec.mirror>
Used by: `src/ZonyLrcTools.Common/MusicDecryption/Kugou/`
(`TcTea.cs`, `EkeyDecoder.cs`, `Qmc2Cipher.cs`, `KugouEkeyDatabase.cs`,
`KggMusicDecryptor.cs`)
The C# classes above are a port of the TC-TEA / ekey / QMC2 / KGMusicV3.db
algorithms from that project. They were rewritten for this codebase (different
structure, streaming I/O, cancellation support), but the cryptographic
constants and the database page-decryption scheme originate there.
```
MIT License
Copyright (c) 2024 LSR
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
@@ -1,6 +1,7 @@
using MusicDecrypto.Library; using MusicDecrypto.Library;
using ZonyLrcTools.Common.Infrastructure.DependencyInject; using ZonyLrcTools.Common.Infrastructure.DependencyInject;
using ZonyLrcTools.Common.Infrastructure.Logging; using ZonyLrcTools.Common.Infrastructure.Logging;
using ZonyLrcTools.Common.MusicDecryption.Kugou;
namespace ZonyLrcTools.Common.MusicDecryption namespace ZonyLrcTools.Common.MusicDecryption
{ {
@@ -8,20 +9,30 @@ namespace ZonyLrcTools.Common.MusicDecryption
public class DefaultMusicDecryptor : IMusicDecryptor, ITransientDependency public class DefaultMusicDecryptor : IMusicDecryptor, ITransientDependency
{ {
private readonly IWarpLogger _warpLogger; private readonly IWarpLogger _warpLogger;
private readonly IKugouKeyProvider? _kugouKeyProvider;
public DefaultMusicDecryptor(IWarpLogger warpLogger) public DefaultMusicDecryptor(IWarpLogger warpLogger, IKugouKeyProvider? kugouKeyProvider = null)
{ {
_warpLogger = warpLogger; _warpLogger = warpLogger;
_kugouKeyProvider = kugouKeyProvider;
} }
public async Task<DecryptionResult> ConvertMusicAsync(string filePath) public async Task<DecryptionResult> ConvertMusicAsync(string filePath, CancellationToken cancellationToken = default)
{ {
try try
{ {
cancellationToken.ThrowIfCancellationRequested();
// .kgg 的密钥存放在酷狗客户端数据库里,MusicDecrypto 覆盖不到这条链路。
if (KggMusicDecryptor.IsKggFile(filePath))
{
return await KggMusicDecryptor.ConvertAsync(filePath, _kugouKeyProvider, cancellationToken);
}
await using var buffer = new MarshalMemoryStream(); await using var buffer = new MarshalMemoryStream();
await using var file = new FileStream(filePath, FileMode.Open, FileAccess.Read); await using var file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
buffer.SetLengthWithPadding(file.Length); buffer.SetLengthWithPadding(file.Length);
await file.CopyToAsync(buffer); await file.CopyToAsync(buffer, cancellationToken);
using var decrypto = DecryptoFactory.Create(buffer, Path.GetFileName(filePath), message => { }); using var decrypto = DecryptoFactory.Create(buffer, Path.GetFileName(filePath), message => { });
var outFileName = (await decrypto.DecryptAsync()).NewName; var outFileName = (await decrypto.DecryptAsync()).NewName;
@@ -30,11 +41,16 @@ namespace ZonyLrcTools.Common.MusicDecryption
if (!File.Exists(outFilePath)) if (!File.Exists(outFilePath))
{ {
await using var outFile = new FileStream(outFilePath, FileMode.Create, FileAccess.Write, FileShare.None); await using var outFile = new FileStream(outFilePath, FileMode.Create, FileAccess.Write, FileShare.None);
await buffer.CopyToAsync(outFile); await buffer.CopyToAsync(outFile, cancellationToken);
} }
return DecryptionResult.Success(outFilePath); return DecryptionResult.Success(outFilePath);
} }
catch (OperationCanceledException)
{
// 用户主动取消,交给调用方区分处理。
throw;
}
catch (Exception e) catch (Exception e)
{ {
return DecryptionResult.Failed(e.Message); return DecryptionResult.Failed(e.Message);
@@ -0,0 +1,63 @@
namespace ZonyLrcTools.Common.MusicDecryption
{
/// <summary>
/// 酷狗数据库的探测结果。
/// </summary>
/// <param name="IsAvailable">数据库是否可用(文件存在且能解出密钥)。</param>
/// <param name="DatabasePath">实际生效的数据库路径;不可用时为 null。</param>
/// <param name="KeyCount">能从数据库里读出的密钥条目数量。</param>
/// <param name="Message">给用户看的说明文字。</param>
public sealed record KugouDatabaseInfo(bool IsAvailable, string? DatabasePath, int KeyCount, string Message);
/// <summary>
/// .kgg 解密前置条件的查询入口。
/// <remarks>
/// .kgg 的音频用 QMC2 加密,而每个文件自己的 ekey 不在文件里,
/// 需要从酷狗客户端本地的 KGMusicV3.db 里按音频哈希查出来。
/// GUI 需要提前知道“库在不在、这个文件有没有密钥”,才能在用户点开始之前给出提示。
/// </remarks>
/// </summary>
public interface IKugouKeyProvider
{
/// <summary>
/// 当前生效的数据库路径;没有可用数据库时为 null。
/// </summary>
string? DatabasePath { get; }
/// <summary>
/// 手动指定数据库路径;<c>null</c> 或空字符串表示恢复自动探测。
/// </summary>
void SetDatabasePath(string? path);
/// <summary>
/// 探测当前可用的数据库。
/// <remarks>
/// 实现应当缓存结果:整库解密需要几十毫秒,而查一次密钥只要零点几毫秒。
/// </remarks>
/// </summary>
KugouDatabaseInfo Probe();
/// <summary>
/// 作废缓存,让下一次访问重新读取数据库。
/// <remarks>
/// 用户在酷狗里新下载了歌曲、或换了一份数据库文件之后需要调用,否则读到的还是旧快照。
/// </remarks>
/// </summary>
void Invalidate();
/// <summary>
/// 判断文件是否是 .kgg(按魔数,不看扩展名)。
/// </summary>
bool IsKggFile(string filePath);
/// <summary>
/// 读出 .kgg 文件头里的音频哈希;不是合法的 .kgg 时返回 null。
/// </summary>
string? ReadAudioHash(string filePath);
/// <summary>
/// 取出该音频哈希对应的 ekey;没有时返回 null。
/// </summary>
string? FindKey(string audioHash);
}
}
@@ -1,4 +1,4 @@
using MusicDecrypto.Library; using MusicDecrypto.Library;
namespace ZonyLrcTools.Common.MusicDecryption namespace ZonyLrcTools.Common.MusicDecryption
{ {
@@ -14,7 +14,8 @@ namespace ZonyLrcTools.Common.MusicDecryption
/// 将加密数据歌曲文件转换为可识别的歌曲格式。 /// 将加密数据歌曲文件转换为可识别的歌曲格式。
/// </summary> /// </summary>
/// <param name="filePath">加密歌曲文件的路径。</param> /// <param name="filePath">加密歌曲文件的路径。</param>
/// <param name="cancellationToken">取消令牌,用于中断大文件的转换。</param>
/// <returns>转换结果。</returns> /// <returns>转换结果。</returns>
Task<DecryptionResult> ConvertMusicAsync(string filePath); Task<DecryptionResult> ConvertMusicAsync(string filePath, CancellationToken cancellationToken = default);
} }
} }
@@ -0,0 +1,204 @@
// Ported from the MIT-licensed reference implementation:
// https://github.com/lizipeng0013/kgg-dec.mirror
// Copyright (c) 2024 LSR
// The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root.
using System.Text;
namespace ZonyLrcTools.Common.MusicDecryption.Kugou
{
/// <summary>
/// 酷狗/QQ 音乐的 ekey 解码器。
/// </summary>
internal static class EkeyDecoder
{
/// <summary>
/// V2 前缀,解码后即 "QQMusic EncV2,Key:"。
/// </summary>
private static readonly byte[] V2Prefix = "UVFNdXNpYyBFbmNWMixLZXk6"u8.ToArray();
private static readonly byte[] V2Key1 =
[
0x33, 0x38, 0x36, 0x5A, 0x4A, 0x59, 0x21, 0x40, 0x23, 0x2A, 0x24, 0x25, 0x5E, 0x26, 0x29, 0x28
];
private static readonly byte[] V2Key2 =
[
0x2A, 0x2A, 0x23, 0x21, 0x28, 0x23, 0x24, 0x25, 0x26, 0x5E, 0x61, 0x31, 0x63, 0x5A, 0x2C, 0x54
];
/// <summary>
/// 将数据库中的 ekey 字符串还原为 QMC2 使用的原始密钥。
/// </summary>
/// <returns>原始密钥;解码失败时为空数组。</returns>
public static byte[] Decode(string ekey) => Decode(ekey, out _);
/// <summary>
/// 将数据库中的 ekey 字符串还原为 QMC2 使用的原始密钥。
/// <param name="invalidCharCount">
/// Base64 段里被忽略的非法字符数量。Base64 解码本身是宽容的(会静默映射成 0),
/// 这里把它统计出来,让上层能把「密钥损坏」和「没有密钥」区分开。
/// </param>
/// </summary>
/// <returns>原始密钥;解码失败时为空数组。</returns>
public static byte[] Decode(string ekey, out int invalidCharCount)
{
invalidCharCount = 0;
if (string.IsNullOrEmpty(ekey))
{
return [];
}
var raw = Encoding.Latin1.GetBytes(ekey);
if (raw.Length >= V2Prefix.Length && raw.AsSpan(0, V2Prefix.Length).SequenceEqual(V2Prefix))
{
var inner = TcTea.CbcDecrypt(raw[V2Prefix.Length..], TcTea.ToRoundKeys(V2Key1));
if (inner.Length == 0)
{
return [];
}
inner = TcTea.CbcDecrypt(inner, TcTea.ToRoundKeys(V2Key2));
if (inner.Length == 0)
{
return [];
}
return DecodeV1(Encoding.Latin1.GetString(inner), out invalidCharCount);
}
return DecodeV1(ekey, out invalidCharCount);
}
private static byte[] DecodeV1(string ekey, out int invalidCharCount)
{
var result = Base64Decode(Encoding.Latin1.GetBytes(ekey), out invalidCharCount);
if (result.Length < 8)
{
return [];
}
var teaKey = new[]
{
0x69005600u | ((uint)result[0] << 16) | result[1],
0x46003800u | ((uint)result[2] << 16) | result[3],
0x2b002000u | ((uint)result[4] << 16) | result[5],
0x15000b00u | ((uint)result[6] << 16) | result[7]
};
var decrypted = TcTea.CbcDecrypt(result[8..], teaKey);
if (decrypted.Length == 0)
{
return [];
}
var output = new byte[8 + decrypted.Length];
result.AsSpan(0, 8).CopyTo(output);
decrypted.CopyTo(output.AsSpan(8));
return output;
}
private static readonly byte[] Base64Table =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"u8.ToArray();
/// <summary>
/// 宽容的 Base64 解码,兼容 URL-safe 变体与不规范的长度。
/// <param name="invalidCount">输入中不属于 Base64 的字符数量(空白字符会被跳过,不计入)。</param>
/// </summary>
private static byte[] Base64Decode(byte[] input, out int invalidCount)
{
var reverse = new byte[256];
var isKnown = new bool[256];
for (var i = 0; i < Base64Table.Length; i++)
{
reverse[Base64Table[i]] = (byte)i;
isKnown[Base64Table[i]] = true;
}
// URL-safe 变体。
reverse[(byte)'-'] = 62;
reverse[(byte)'_'] = 63;
isKnown[(byte)'-'] = true;
isKnown[(byte)'_'] = true;
isKnown[(byte)'='] = true;
// 空白字符按「忽略」处理,其余未知字符计入 invalidCount,交给调用方判定为损坏。
isKnown[(byte)' '] = true;
isKnown[(byte)'\r'] = true;
isKnown[(byte)'\n'] = true;
isKnown[(byte)'\t'] = true;
invalidCount = 0;
var cleaned = new byte[input.Length];
var cleanedLength = 0;
foreach (var value in input)
{
if (value is (byte)' ' or (byte)'\r' or (byte)'\n' or (byte)'\t')
{
continue;
}
if (!isKnown[value])
{
invalidCount++;
continue;
}
cleaned[cleanedLength++] = value;
}
input = cleaned.AsSpan(0, cleanedLength).ToArray();
var output = new byte[(input.Length + 3) / 4 * 3];
var outOffset = 0;
// 解一组 4 个字符;返回 true 表示遇到了填充,可以结束。
bool DecodeBlock(ReadOnlySpan<byte> block)
{
var a = reverse[block[0]];
var b = reverse[block[1]];
var c = reverse[block[2]];
var d = reverse[block[3]];
output[outOffset++] = (byte)((a << 2) | (b >> 4));
if (block[2] == '=')
{
return true;
}
output[outOffset++] = (byte)((b << 4) | (c >> 2));
if (block[3] == '=')
{
return true;
}
output[outOffset++] = (byte)((c << 6) | d);
return false;
}
var fullLength = input.Length - input.Length % 4;
for (var i = 0; i < fullLength; i += 4)
{
if (DecodeBlock(input.AsSpan(i, 4)))
{
return output.AsSpan(0, outOffset).ToArray();
}
}
var remainder = input.Length % 4;
if (remainder != 0)
{
var tail = new byte[4];
tail[0] = input[fullLength];
tail[1] = remainder > 1 ? input[fullLength + 1] : (byte)'=';
tail[2] = (byte)'=';
tail[3] = (byte)'=';
DecodeBlock(tail);
}
return output.AsSpan(0, outOffset).ToArray();
}
}
}
@@ -0,0 +1,239 @@
// Ported from the MIT-licensed reference implementation:
// https://github.com/lizipeng0013/kgg-dec.mirror
// Copyright (c) 2024 LSR
// The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root.
using System.Buffers.Binary;
using System.Text;
namespace ZonyLrcTools.Common.MusicDecryption.Kugou
{
/// <summary>
/// 酷狗 .kgg 文件的解密器。
/// <remarks>
/// .kgg 的音频主体用 QMC2 加密,而每个文件自己的 ekey 并不在文件里,
/// 需要从酷狗客户端本地的 KGMusicV3.db 中按音频哈希查出来。
/// 因此这个格式无法脱离酷狗客户端单独解密。
/// </remarks>
/// </summary>
internal static class KggMusicDecryptor
{
private const int HeaderSize = KugouEkeyDatabase.KggHeaderSize;
private const int BufferSize = 1024 * 1024;
private const uint ExpectedEncodingVersion = 5;
private const uint ExpectedHashLength = 0x20;
/// <summary>
/// .kgg 文件的 16 字节魔数。
/// </summary>
private static byte[] Magic => KugouEkeyDatabase.KggMagic;
/// <summary>
/// 判断文件是否真的是 .kgg 格式(按魔数而非扩展名)。
/// </summary>
public static bool IsKggFile(string filePath)
{
try
{
using var stream = File.OpenRead(filePath);
Span<byte> buffer = stackalloc byte[16];
return stream.ReadAtLeast(buffer, 16, throwOnEndOfStream: false) == 16
&& buffer.SequenceEqual(Magic);
}
catch
{
return false;
}
}
/// <summary>
/// 解密 .kgg 文件。
/// </summary>
/// <param name="filePath">待解密的文件路径。</param>
/// <param name="keyProvider">密钥来源;为 null 时使用自动探测到的酷狗数据库。</param>
/// <param name="cancellationToken">取消令牌。</param>
/// <returns>解密结果;失败时带有可读的错误说明。</returns>
public static async Task<DecryptionResult> ConvertAsync(string filePath,
IKugouKeyProvider? keyProvider,
CancellationToken cancellationToken)
{
if (!File.Exists(filePath))
{
return DecryptionResult.Failed($"文件不存在: {filePath}");
}
await using var input = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, true);
var header = new byte[HeaderSize];
if (await input.ReadAtLeastAsync(header, HeaderSize, throwOnEndOfStream: false, cancellationToken) !=
HeaderSize)
{
return DecryptionResult.Failed("文件过小,不是有效的 kgg 文件。");
}
if (!header.AsSpan(0, Magic.Length).SequenceEqual(Magic))
{
return DecryptionResult.Failed("文件头校验失败,不是有效的 kgg 文件。");
}
var offsetToAudio = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x10));
var encodingVersion = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x14));
if (encodingVersion != ExpectedEncodingVersion)
{
return DecryptionResult.Failed($"不支持的 kgg 加密版本 0x{encodingVersion:X2},目前只支持 0x05。");
}
var hashLength = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x44));
if (hashLength != ExpectedHashLength)
{
return DecryptionResult.Failed($"kgg 音频哈希长度异常(期望 0x20,实际 0x{hashLength:X2})。");
}
var audioHash = Encoding.ASCII.GetString(header, 0x48, (int)hashLength);
if (!HasDatabase(keyProvider))
{
return DecryptionResult.Failed(KugouEkeyDatabase.BuildMissingDatabaseMessage());
}
var ekey = ResolveEkey(keyProvider, audioHash);
if (string.IsNullOrEmpty(ekey))
{
return DecryptionResult.Failed(
$"在酷狗数据库中没有找到该文件的解密密钥(音频哈希 {audioHash})。" +
"通常表示这首歌尚未在酷狗客户端里播放或下载过。");
}
var qmcKey = EkeyDecoder.Decode(ekey, out var invalidCharCount);
if (invalidCharCount > 0)
{
return DecryptionResult.Failed(
$"酷狗数据库里的 ekey 已损坏(有 {invalidCharCount} 个非法 Base64 字符),无法解码。" +
"通常表示数据库文件被写坏了,可以尝试重新登录酷狗客户端刷新该记录。");
}
var cipher = Qmc2Cipher.Create(qmcKey);
if (cipher == null)
{
return DecryptionResult.Failed("ekey 解码失败,无法构造解密器。");
}
input.Seek(offsetToAudio, SeekOrigin.Begin);
// 先解密开头 4 字节用于判断真实格式,再回去完整解密一遍。
var magic = new byte[4];
if (await input.ReadAtLeastAsync(magic, 4, throwOnEndOfStream: false, cancellationToken) != 4)
{
return DecryptionResult.Failed("kgg 音频数据为空。");
}
cipher.Decrypt(magic, 0);
var extension = DetectExtension(magic);
input.Seek(offsetToAudio, SeekOrigin.Begin);
var outputPath = Path.Combine(
Path.GetDirectoryName(filePath)!,
$"{Path.GetFileNameWithoutExtension(filePath)}.{extension}");
// 期望的输出字节数,用于校验写盘是否完整。
var expectedLength = input.Length - offsetToAudio;
// 目标已存在且大小正确就不再覆盖,避免重复解密白费时间。
// 只要大小对不上(例如上次被中途取消留下的半截文件),就重新解密覆盖。
if (File.Exists(outputPath) && new FileInfo(outputPath).Length == expectedLength)
{
return DecryptionResult.Success(outputPath);
}
// 先写临时文件,成功后再改名。中途取消或被强杀都不会污染正式输出文件名。
var tempPath = outputPath + ".part";
try
{
await using (var output = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None,
BufferSize, true))
{
var buffer = new byte[BufferSize];
long offset = 0;
int read;
while ((read = await input.ReadAsync(buffer, cancellationToken)) > 0)
{
cipher.Decrypt(buffer.AsSpan(0, read), offset);
await output.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
offset += read;
}
await output.FlushAsync(cancellationToken);
if (offset != expectedLength)
{
throw new IOException($"解密写入的字节数不匹配(期望 {expectedLength},实际 {offset})。");
}
}
File.Move(tempPath, outputPath, overwrite: true);
}
catch
{
TryDelete(tempPath);
throw;
}
return DecryptionResult.Success(outputPath);
}
private static void TryDelete(string path)
{
try
{
if (File.Exists(path))
{
File.Delete(path);
}
}
catch
{
// 清理失败不影响主流程,下次解密会覆盖这个临时文件。
}
}
private static bool HasDatabase(IKugouKeyProvider? keyProvider)
{
return keyProvider?.DatabasePath != null || KugouEkeyDatabase.FindDatabasePath() != null;
}
/// <summary>
/// 取出音频哈希对应的 ekey;优先走外部提供的密钥来源。
/// </summary>
public static string? ResolveEkey(IKugouKeyProvider? keyProvider, string audioHash)
{
if (keyProvider != null)
{
return keyProvider.FindKey(audioHash);
}
var databasePath = KugouEkeyDatabase.FindDatabasePath();
if (databasePath == null)
{
return null;
}
var keys = KugouEkeyDatabase.ReadEncryptionKeys(databasePath);
return keys.TryGetValue(audioHash, out var ekey) ? ekey : null;
}
private static string DetectExtension(ReadOnlySpan<byte> magic)
{
if (magic.SequenceEqual("fLaC"u8))
{
return "flac";
}
if (magic.SequenceEqual("OggS"u8))
{
return "ogg";
}
return "mp3";
}
}
}
@@ -0,0 +1,353 @@
// Ported from the MIT-licensed reference implementation:
// https://github.com/lizipeng0013/kgg-dec.mirror
// Copyright (c) 2024 LSR
// The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root.
using System.Buffers.Binary;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Data.Sqlite;
namespace ZonyLrcTools.Common.MusicDecryption.Kugou
{
/// <summary>
/// 酷狗客户端本地数据库(KGMusicV3.db)的读取器。
/// <remarks>
/// 数据库按 4KB 分页做了 AES-128-CBC 加密,每页的密钥与 IV 由主密钥 + 页号派生。
/// 解密后可以读到 <c>ShareFileItems</c> 表里的 ekey,那是 .kgg 文件真正用的解密密钥。
/// </remarks>
/// </summary>
internal static class KugouEkeyDatabase
{
/// <summary>
/// .kgg 文件头的长度,音频数据从这个位置之后开始。
/// </summary>
internal const int KggHeaderSize = 0x400;
/// <summary>
/// .kgg 文件的 16 字节魔数。
/// </summary>
internal static readonly byte[] KggMagic =
[
0x7C, 0xD5, 0x32, 0xEB, 0x86, 0x02, 0x7F, 0x4B,
0xA8, 0xAF, 0xA6, 0x8E, 0x0F, 0xFF, 0x99, 0x14
];
private const int PageSize = 0x400;
private const uint PageKeySalt = 0x546C4173;
private const uint IvMultiplier = 0x7FFFFF07;
private const uint IvDivisor = 0xce26;
private const uint IvBase = 0x9EF4;
/// <summary>
/// 酷狗客户端内置的主密钥。
/// </summary>
private static readonly byte[] MasterKey =
[
0x1d, 0x61, 0x31, 0x45, 0xb2, 0x47, 0xbf, 0x7f,
0x3d, 0x18, 0x96, 0x72, 0x14, 0x4f, 0xe4, 0xbf
];
private static readonly byte[] SqliteHeader =
[
(byte)'S', (byte)'Q', (byte)'L', (byte)'i', (byte)'t', (byte)'e', (byte)' ',
(byte)'f', (byte)'o', (byte)'r', (byte)'m', (byte)'a', (byte)'t', (byte)' ', (byte)'3', 0
];
/// <summary>
/// 从数据库里读出所有非空的 ekey。
/// </summary>
/// <returns>音频哈希到 ekey 的映射;文件不存在或解密失败时返回空字典。</returns>
public static IReadOnlyDictionary<string, string> ReadEncryptionKeys(string databasePath)
{
return ReadEncryptionKeys(databasePath, out _);
}
/// <summary>
/// 从数据库里读出所有非空的 ekey,并在失败时给出可读的原因。
/// <remarks>
/// 读取失败的原因有多种(文件不存在 / 不是酷狗数据库 / 主密钥不匹配 / 表结构缺失 / 权限不足),
/// 这些在 UI 上的处置完全不同,因此不能再把所有异常压成「没有密钥」。
/// </remarks>
/// </summary>
/// <param name="databasePath">数据库文件路径。</param>
/// <param name="failureReason">读取失败时的原因说明;成功时为 null。</param>
public static IReadOnlyDictionary<string, string> ReadEncryptionKeys(string databasePath, out string? failureReason)
{
failureReason = null;
var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (string.IsNullOrWhiteSpace(databasePath))
{
failureReason = "没有指定酷狗数据库路径。";
return result;
}
if (!File.Exists(databasePath))
{
failureReason = $"数据库文件不存在:{databasePath}";
return result;
}
byte[] plain;
try
{
plain = DecryptDatabase(databasePath);
}
catch (Exception ex)
{
failureReason = $"数据库解密失败(文件可能不是酷狗 KGMusicV3.db,或版本不受支持):{ex.Message}";
return result;
}
if (plain.Length == 0)
{
failureReason = $"数据库解密后内容为空,格式不像酷狗 KGMusicV3.db:{databasePath}";
return result;
}
// 解密后的内容写到临时文件,交给 SQLite 自己解析,避免手写记录格式。
// 这里放的是明文密钥库,所以用一个专用目录并在每次进入时清理上次留下的残留:
// 进程被强杀时 finally 不会执行,但下一次读取会把上一轮的明文文件删掉。
var tempDirectory = Path.Combine(Path.GetTempPath(), TemporaryDirectoryName);
var tempPath = Path.Combine(tempDirectory, $"{Guid.NewGuid():N}.db");
try
{
Directory.CreateDirectory(tempDirectory);
SweepStaleTempFiles(tempDirectory);
WriteFileWithFlush(tempPath, plain);
using var connection = new SqliteConnection($"Data Source={tempPath};Mode=ReadOnly");
connection.Open();
using var command = connection.CreateCommand();
command.CommandText = "select EncryptionKeyId, EncryptionKey from ShareFileItems where EncryptionKey != ''";
using var reader = command.ExecuteReader();
while (reader.Read())
{
if (reader.IsDBNull(0) || reader.IsDBNull(1))
{
continue;
}
var keyId = reader.GetString(0);
var ekey = reader.GetString(1);
if (keyId.Length > 0 && ekey.Length > 0)
{
result[keyId] = ekey;
}
}
}
catch (Exception ex)
{
failureReason = $"数据库内容读取失败(表 ShareFileItems 可能不存在):{ex.Message}";
return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
finally
{
TryDeleteFile(tempPath);
}
return result;
}
private const string TemporaryDirectoryName = "zony-kgm-temp";
private static void WriteFileWithFlush(string path, byte[] content)
{
using var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read);
stream.Write(content, 0, content.Length);
stream.Flush(true);
}
/// <summary>
/// 清掉上一次运行留下的明文临时库(正常退出时 finally 已经删过,这里只兜异常退出的底)。
/// </summary>
private static void SweepStaleTempFiles(string directory)
{
try
{
foreach (var file in Directory.EnumerateFiles(directory, "*.db"))
{
TryDeleteFile(file);
}
}
catch
{
// 目录枚举失败不影响本次读取。
}
}
private static void TryDeleteFile(string path)
{
try
{
if (File.Exists(path))
{
File.Delete(path);
}
}
catch
{
// 删不掉不影响结果,下次进入时还会再清一次。
}
}
/// <summary>
/// 把整个加密数据库解密成明文的 SQLite 字节流。
/// </summary>
private static byte[] DecryptDatabase(string databasePath)
{
using var source = new FileStream(databasePath, FileMode.Open, FileAccess.Read, FileShare.Read);
var length = (int)source.Length;
if (length == 0 || length % PageSize != 0)
{
return [];
}
var pageCount = length / PageSize;
var plain = new byte[length];
var headerBuffer = new byte[8];
// 复用同一个 Aes 实例:每页只是换 Key,避免 16000+ 次 Aes.Create() 的对象构造开销。
using var aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.None;
for (var pageIndex = 1; pageIndex <= pageCount; pageIndex++)
{
var target = plain.AsSpan((pageIndex - 1) * PageSize, PageSize);
source.ReadExactly(target);
DerivePageKeyIv((uint)pageIndex, out var key, out var iv);
if (pageIndex == 1)
{
// 首页前 16 字节是明文文件头,真正从 0x10 开始加密;
// 解密前要把 0x08..0x10 复制到 0x10 处作为 CBC 的密文块。
target.Slice(0x10, 8).CopyTo(headerBuffer);
target.Slice(0x08, 8).CopyTo(target[0x10..]);
AesCbcDecryptInPlace(aes, target[0x10..], key, iv);
if (!target.Slice(0x10, 8).SequenceEqual(headerBuffer))
{
return [];
}
SqliteHeader.CopyTo(target);
}
else
{
AesCbcDecryptInPlace(aes, target, key, iv);
}
}
return plain;
}
private static void AesCbcDecryptInPlace(Aes aes, Span<byte> buffer, byte[] key, byte[] iv)
{
aes.Key = key;
// 两个坑都要显式避开:
// 1) 参数顺序是 TryDecryptCbc(ciphertext, iv, destination, out written, padding),
// 写成 (buffer, buffer, iv, ...) 会把 buffer 自己当 IV、把真正的 IV 覆盖掉;
// 2) padding 的默认值是 PKCS7 而不是实例上的 aes.Padding,分页数据是整块无填充的,
// 不传 PaddingMode.None 就会在每页末尾抛「Padding is invalid」。
if (!aes.TryDecryptCbc(buffer, iv, buffer, out var written, PaddingMode.None) ||
written != buffer.Length)
{
throw new CryptographicException("酷狗数据库分页解密失败。");
}
}
/// <summary>
/// 按页号派生出该页使用的 AES 密钥与 IV。
/// </summary>
private static void DerivePageKeyIv(uint pageNumber, out byte[] key, out byte[] iv)
{
var buffer = new byte[0x18];
MasterKey.CopyTo(buffer, 0);
BinaryPrimitives.WriteUInt32LittleEndian(buffer.AsSpan(0x10), pageNumber);
BinaryPrimitives.WriteUInt32LittleEndian(buffer.AsSpan(0x14), PageKeySalt);
key = MD5.HashData(buffer);
// IV 由一个线性同余式的四次迭代结果拼成。
var value = pageNumber + 1;
for (var i = 0; i < 16; i += 4)
{
unchecked
{
var quotient = value / IvDivisor;
var product = IvMultiplier * quotient;
var next = IvBase * value - product;
if ((next & 0x8000_0000) != 0)
{
next += IvMultiplier;
}
value = next;
BinaryPrimitives.WriteUInt32LittleEndian(buffer.AsSpan(i), value);
}
}
iv = MD5.HashData(buffer.AsSpan(0, 0x10));
}
/// <summary>
/// 酷狗客户端数据库的常见位置。
/// </summary>
public static IEnumerable<string> EnumerateCandidatePaths()
{
var roaming = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
if (!string.IsNullOrEmpty(roaming))
{
yield return Path.Combine(roaming, "KuGou8", "KGMusicV3.db");
yield return Path.Combine(roaming, "KuGou", "KGMusicV3.db");
}
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
if (!string.IsNullOrEmpty(localAppData))
{
yield return Path.Combine(localAppData, "KuGou8", "KGMusicV3.db");
yield return Path.Combine(localAppData, "KuGou", "KGMusicV3.db");
}
}
/// <summary>
/// 找到第一个存在的数据库路径。
/// </summary>
public static string? FindDatabasePath()
{
foreach (var path in EnumerateCandidatePaths())
{
if (File.Exists(path))
{
return path;
}
}
return null;
}
/// <summary>
/// 让用户能看懂的错误信息。
/// </summary>
public static string BuildMissingDatabaseMessage()
{
var builder = new StringBuilder();
builder.Append("未找到酷狗客户端数据库 KGMusicV3.db,无法获取解密密钥。");
builder.Append("请确认已安装酷狗音乐并至少登录过一次。已尝试的路径:");
foreach (var path in EnumerateCandidatePaths())
{
builder.Append(' ').Append(path).Append(';');
}
return builder.ToString();
}
}
}
@@ -0,0 +1,252 @@
// Ported from the MIT-licensed reference implementation:
// https://github.com/lizipeng0013/kgg-dec.mirror
// Copyright (c) 2024 LSR
// The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root.
using System.Buffers.Binary;
namespace ZonyLrcTools.Common.MusicDecryption.Kugou
{
/// <summary>
/// QMC2 加密流的解密器基类,负责按偏移量流式解出明文。
/// </summary>
internal abstract class Qmc2Cipher
{
/// <summary>
/// 首段的长度,这一段的密钥派生方式与其他段不同。
/// </summary>
protected const int FirstSegmentSize = 0x80;
/// <summary>
/// 其余段落的长度。
/// </summary>
protected const int OtherSegmentSize = 0x1400;
/// <summary>
/// 解密数据流中的一个字节。
/// </summary>
/// <param name="cipher">密文中的该字节。</param>
/// <param name="offset">该字节在完整音频流中的偏移量。</param>
public abstract byte Decrypt(byte cipher, long offset);
/// <summary>
/// 就地把一段数据解密。
/// <remarks>
/// 批量接口,避免逐字节走虚函数调用;几十 MB 的文件靠逐字节会慢到不可接受。
/// </remarks>
/// </summary>
/// <param name="data">待解密的密文,解密结果原地写回。</param>
/// <param name="offset">这段数据在完整音频流中的起始偏移量。</param>
public virtual void Decrypt(Span<byte> data, long offset)
{
for (var i = 0; i < data.Length; i++)
{
data[i] = Decrypt(data[i], offset + i);
}
}
/// <summary>
/// 根据解码后的 ekey 长度选择具体的实现。
/// </summary>
public static Qmc2Cipher? Create(byte[] key)
{
if (key.Length == 0)
{
return null;
}
return key.Length < 300 ? new Qmc2MapCipher(key) : new Qmc2Rc4Cipher(key);
}
}
/// <summary>
/// 短密钥(长度小于 300)使用的查表型解密器。
/// </summary>
internal sealed class Qmc2MapCipher : Qmc2Cipher
{
private const int MapIndexOffset = 71214;
private const int MapKeySize = 128;
private const int MapIndexBoundary = 0x7FFF;
private readonly byte[] _key;
public Qmc2MapCipher(byte[] key)
{
_key = new byte[MapKeySize];
var length = key.Length;
for (var i = 0; i < MapKeySize; i++)
{
var j = (int)(((long)i * i + MapIndexOffset) % length);
var shift = (j + 4) % 8;
var value = key[j];
_key[i] = (byte)((value << shift) | (value >> (8 - shift)));
}
}
public override byte Decrypt(byte cipher, long offset)
{
var index = offset <= MapIndexBoundary ? offset : offset % MapIndexBoundary;
return (byte)(cipher ^ _key[index % MapKeySize]);
}
public override void Decrypt(Span<byte> data, long offset)
{
for (var i = 0; i < data.Length; i++)
{
var position = offset + i;
var index = position <= MapIndexBoundary ? position : position % MapIndexBoundary;
data[i] ^= _key[index % MapKeySize];
}
}
}
/// <summary>
/// 长密钥使用的 RC4 派生流解密器。
/// </summary>
internal sealed class Qmc2Rc4Cipher : Qmc2Cipher
{
/// <summary>
/// 每段从密钥流中取用的前置长度上限。
/// </summary>
private const int SegmentSkipMask = 0x1FF;
/// <summary>
/// 密钥流的长度,比普通段多出 512 字节用于起始偏移。
/// </summary>
private const int KeyStreamSize = OtherSegmentSize + 512;
private readonly byte[] _key;
private readonly byte[] _keyStream = new byte[KeyStreamSize];
private readonly uint _keyHash;
public Qmc2Rc4Cipher(byte[] key)
{
_key = key;
_keyHash = ComputeKeyHash(key);
DeriveKeyStream();
}
public override byte Decrypt(byte cipher, long offset)
{
if (offset < FirstSegmentSize)
{
// 首段的索引直接由当前偏移推导,且随偏移逐字节变化。
var seed = _key[(int)(offset % _key.Length)];
var index = GetSegmentKey(_keyHash, offset, seed) % _key.Length;
return (byte)(cipher ^ _key[index]);
}
var segmentIndex = offset / OtherSegmentSize;
var segmentOffset = offset % OtherSegmentSize;
var skipLength = GetSegmentKey(_keyHash, segmentIndex, _key[segmentIndex % _key.Length]) & SegmentSkipMask;
return (byte)(cipher ^ _keyStream[skipLength + segmentOffset]);
}
public override void Decrypt(Span<byte> data, long offset)
{
// 首段与常规段的算法不同,先按边界切一刀。
if (offset < FirstSegmentSize)
{
var length = (int)Math.Min(data.Length, FirstSegmentSize - offset);
for (var i = 0; i < length; i++)
{
var seed = _key[(int)((offset + i) % _key.Length)];
var index = GetSegmentKey(_keyHash, offset + i, seed) % _key.Length;
data[i] ^= _key[index];
}
offset += length;
data = data[length..];
}
while (data.Length > 0)
{
var segmentIndex = offset / OtherSegmentSize;
var segmentOffset = (int)(offset % OtherSegmentSize);
var skipLength = GetSegmentKey(_keyHash, segmentIndex, _key[segmentIndex % _key.Length]) & SegmentSkipMask;
var length = Math.Min(data.Length, OtherSegmentSize - segmentOffset);
var stream = _keyStream.AsSpan((int)skipLength + segmentOffset, length);
for (var i = 0; i < length; i++)
{
data[i] ^= stream[i];
}
offset += length;
data = data[length..];
}
}
/// <summary>
/// 把密钥压成一个 32 位的乘法哈希,遇到溢出就提前结束。
/// </summary>
private static uint ComputeKeyHash(ReadOnlySpan<byte> key)
{
uint hash = 1;
foreach (var item in key)
{
if (item == 0)
{
continue;
}
var next = hash * item;
if (next <= hash)
{
break;
}
hash = next;
}
return hash;
}
/// <summary>
/// 按段号与种子计算出该段在密钥或密钥流中的起始位置。
/// <remarks>
/// 中间结果可能远超 int 上限,必须用 long 承载,否则会截断出错位。
/// </remarks>
/// </summary>
private static long GetSegmentKey(uint hash, long segmentId, int seed)
{
if (seed == 0)
{
return 0;
}
return (long)(hash / (double)(seed * (segmentId + 1)) * 100.0);
}
/// <summary>
/// 用 RC4 的 KSA 生成密钥流。
/// </summary>
private void DeriveKeyStream()
{
var length = _key.Length;
var state = new byte[length];
for (var i = 0; i < length; i++)
{
state[i] = (byte)i;
}
// 这里的 i / j 必须是宽于 byte 的整数,长度 512 时 byte 会回绕。
var j = 0;
for (var i = 0; i < length; i++)
{
j = (j + state[i] + _key[i]) % length;
(state[i], state[j]) = (state[j], state[i]);
}
var a = 0;
var b = 0;
for (var i = 0; i < KeyStreamSize; i++)
{
a = (a + 1) % length;
b = (b + state[a]) % length;
(state[a], state[b]) = (state[b], state[a]);
_keyStream[i] = state[(state[a] + state[b]) % length];
}
}
}
}
@@ -0,0 +1,139 @@
// Ported from the MIT-licensed reference implementation:
// https://github.com/lizipeng0013/kgg-dec.mirror
// Copyright (c) 2024 LSR
// The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root.
using System.Buffers.Binary;
namespace ZonyLrcTools.Common.MusicDecryption.Kugou
{
/// <summary>
/// 腾讯 TEA(TC-TEA)加解密实现,用于解析酷狗的 ekey 密文。
/// <remarks>
/// 这里只实现了 QMC2 所需的部分:单块 ECB 解密与带双 IV 链的 CBC 解密。
/// 算法来源于酷狗客户端的实际行为,与 MusicDecrypto 内置的格式无关。
/// </remarks>
/// </summary>
internal static class TcTea
{
private const int Rounds = 16;
private const uint Delta = 0x9e3779b9;
/// <summary>
/// 16 轮累加后的 sum 值,等价于 <c>Rounds * Delta</c> 在 uint32 下的溢出结果。
/// </summary>
private const uint ExpectedSum = 0xE3779B90;
private const int BlockSize = 8;
private const int FixedSaltLength = 2;
private const int ZeroPaddingLength = 7;
private const int HeaderSize = BlockSize * 2;
private static uint SingleRound(uint value, uint sum, uint key1, uint key2)
{
return ((value << 4) + key1) ^ (value + sum) ^ ((value >> 5) + key2);
}
/// <summary>
/// TEA 单块解密(ECB)。
/// </summary>
public static ulong DecryptBlock(ulong value, ReadOnlySpan<uint> key)
{
var y = (uint)(value >> 32);
var z = (uint)value;
var sum = ExpectedSum;
for (var i = 0; i < Rounds; i++)
{
z -= SingleRound(y, sum, key[2], key[3]);
y -= SingleRound(z, sum, key[0], key[1]);
sum -= Delta;
}
return ((ulong)y << 32) | z;
}
/// <summary>
/// TC-TEA 的 CBC 解密,带自定义的头部跳过与零填充校验。
/// <remarks>
/// 参数与返回值都用数组而非 Span,是因为内部要用局部函数保存解密状态。
/// </remarks>
/// </summary>
/// <returns>解密后的明文;若校验失败则返回空数组。</returns>
public static byte[] CbcDecrypt(byte[] cipher, uint[] key)
{
// 由于填充方案的特殊性,密文至少要两个块长。
if (cipher.Length % BlockSize != 0 || cipher.Length < HeaderSize)
{
return [];
}
ulong iv1 = 0;
ulong iv2 = 0;
var inOffset = 0;
var header = new byte[HeaderSize];
// 解密一轮,把结果写到 target 指定的 8 字节位置。
void DecryptRound(byte[] target, int targetOffset)
{
var iv1Next = BinaryPrimitives.ReadUInt64BigEndian(cipher.AsSpan(inOffset));
var iv2Next = DecryptBlock(iv1Next ^ iv2, key);
var plain = iv2Next ^ iv1;
iv1 = iv1Next;
iv2 = iv2Next;
BinaryPrimitives.WriteUInt64BigEndian(target.AsSpan(targetOffset), plain);
inOffset += BlockSize;
}
DecryptRound(header, 0);
DecryptRound(header, BlockSize);
var headerSkipLength = 1 + (header[0] & 7) + FixedSaltLength;
var realPlainLength = cipher.Length - headerSkipLength - ZeroPaddingLength;
if (realPlainLength <= 0)
{
return [];
}
var result = new byte[realPlainLength];
// 先拷出头部块里剩余的明文。
var copyLength = Math.Min(HeaderSize - headerSkipLength, realPlainLength);
Array.Copy(header, headerSkipLength, result, 0, copyLength);
var outOffset = copyLength;
if (realPlainLength != copyLength)
{
for (var i = cipher.Length - BlockSize * 3; i != 0; i -= BlockSize)
{
DecryptRound(header, 0);
Array.Copy(header, 0, result, outOffset, BlockSize);
outOffset += BlockSize;
}
// 最后一个块只取首字节,且必须落在 header 的第二个块位置,供下方零填充校验使用。
DecryptRound(header, BlockSize);
result[outOffset] = header[BlockSize];
}
// 校验零填充:末尾 8 字节左移一位后必须为 0。
var verify = BinaryPrimitives.ReadUInt64BigEndian(header.AsSpan(BlockSize)) << 8;
return verify != 0 ? [] : result;
}
/// <summary>
/// 将 16 字节的密钥按大端拆成 4 个 uint32,供 TEA 使用。
/// </summary>
public static uint[] ToRoundKeys(byte[] key)
{
var result = new uint[4];
for (var i = 0; i < 4; i++)
{
result[i] = BinaryPrimitives.ReadUInt32BigEndian(key.AsSpan(i * 4));
}
return result;
}
}
}
@@ -0,0 +1,190 @@
using System.Buffers.Binary;
using System.Text;
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
namespace ZonyLrcTools.Common.MusicDecryption
{
/// <inheritdoc cref="ZonyLrcTools.Common.MusicDecryption.IKugouKeyProvider" />
public class KugouKeyProvider : IKugouKeyProvider, ISingletonDependency
{
private const int HeaderSize = Kugou.KugouEkeyDatabase.KggHeaderSize;
private const int AudioHashOffset = 0x48;
private const int AudioHashLength = 0x20;
private readonly object _syncRoot = new();
private readonly Dictionary<string, string> _keys = new(StringComparer.OrdinalIgnoreCase);
private string? _manualPath;
private string? _databasePath;
private string? _loadedPath;
private string? _failureReason;
private bool _isLoaded;
public string? DatabasePath
{
get
{
lock (_syncRoot)
{
EnsureLoaded();
return _databasePath;
}
}
}
public void SetDatabasePath(string? path)
{
lock (_syncRoot)
{
var normalized = string.IsNullOrWhiteSpace(path) ? null : path;
if (string.Equals(normalized, _manualPath, StringComparison.OrdinalIgnoreCase))
{
// 路径没变就不作废缓存,避免无意义地重新解密 16 MB 数据库。
return;
}
_manualPath = normalized;
Invalidate();
}
}
/// <summary>
/// 探测当前可用的酷狗数据库。
/// <remarks>
/// 结果会被缓存:整库解密需要几十毫秒,而真正查一次密钥只要 0.1 毫秒。
/// 只有在 <see cref="SetDatabasePath"/> 改变了路径、或显式调用 <see cref="Invalidate"/> 时才会重新读取。
/// </remarks>
/// </summary>
public KugouDatabaseInfo Probe()
{
lock (_syncRoot)
{
EnsureLoaded();
if (_databasePath == null)
{
var message = _manualPath != null
? $"指定的酷狗数据库不可用:{_failureReason ?? _manualPath}"
: Kugou.KugouEkeyDatabase.BuildMissingDatabaseMessage();
return new KugouDatabaseInfo(false, null, 0, message);
}
return _keys.Count == 0
? new KugouDatabaseInfo(false, _databasePath, 0,
$"已找到酷狗数据库,但里面没有任何解密密钥:{_databasePath}")
: new KugouDatabaseInfo(true, _databasePath, _keys.Count,
$"已读取 {_keys.Count} 个解密密钥:{_databasePath}");
}
}
/// <summary>
/// 让下一次访问重新读取数据库(例如用户在酷狗里新下载了歌曲)。
/// </summary>
public void Invalidate()
{
lock (_syncRoot)
{
_isLoaded = false;
_keys.Clear();
_databasePath = null;
_loadedPath = null;
_failureReason = null;
}
}
public bool IsKggFile(string filePath) => ReadAudioHash(filePath) != null;
public string? ReadAudioHash(string filePath)
{
try
{
using var stream = File.OpenRead(filePath);
var header = new byte[HeaderSize];
if (stream.ReadAtLeast(header, HeaderSize, throwOnEndOfStream: false) != HeaderSize)
{
return null;
}
if (!header.AsSpan(0, 16).SequenceEqual(Kugou.KugouEkeyDatabase.KggMagic))
{
return null;
}
var hashLength = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x44));
if (hashLength == 0 || hashLength > AudioHashLength)
{
return null;
}
return Encoding.ASCII.GetString(header, AudioHashOffset, (int)hashLength);
}
catch
{
return null;
}
}
public string? FindKey(string audioHash)
{
if (string.IsNullOrEmpty(audioHash))
{
return null;
}
lock (_syncRoot)
{
EnsureLoaded();
return _keys.TryGetValue(audioHash, out var ekey) && !string.IsNullOrEmpty(ekey) ? ekey : null;
}
}
private void EnsureLoaded()
{
if (_isLoaded)
{
return;
}
_isLoaded = true;
_keys.Clear();
_databasePath = null;
_loadedPath = null;
_failureReason = null;
var path = _manualPath;
if (path == null)
{
path = Kugou.KugouEkeyDatabase.FindDatabasePath();
if (path == null)
{
return;
}
}
else if (!File.Exists(path))
{
_failureReason = "文件不存在";
return;
}
var keys = Kugou.KugouEkeyDatabase.ReadEncryptionKeys(path, out var failureReason);
if (keys.Count == 0)
{
_failureReason = failureReason ?? "没有读到任何密钥";
// 手动指定的文件读不出密钥,就不要把它当成可用数据库。
if (_manualPath != null)
{
return;
}
}
_databasePath = path;
_loadedPath = path;
foreach (var pair in keys)
{
_keys[pair.Key] = pair.Value;
}
}
}
}
@@ -7,6 +7,9 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Data.Sqlite"/>
<!-- 直接引用 bundle 以覆盖 Microsoft.Data.Sqlite 传递进来的旧版原生包(消除 NU1903)。 -->
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3"/>
<PackageReference Include="Microsoft.Extensions.Http"/> <PackageReference Include="Microsoft.Extensions.Http"/>
<PackageReference Include="Microsoft.Extensions.Localization"/> <PackageReference Include="Microsoft.Extensions.Localization"/>
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions"/> <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions"/>