feat: use static cipher instead of mask

(cherry picked from commit cd6b84ad7eed489f9bcbd72d847cd4d704052b0c)
This commit is contained in:
MengYX 2021-12-16 07:07:51 +08:00
parent cd3f4d8c22
commit b4068e2edb
5 changed files with 192 additions and 218 deletions

View File

@ -1,12 +1,13 @@
import {QmcMask, QmcMaskGetDefault} from "./qmcMask"; import {QmcStaticCipher} from "./qmc_cipher";
import {toByteArray as Base64Decode} from 'base64-js'
import { import {
AudioMimeType, AudioMimeType,
GetArrayBuffer, GetArrayBuffer,
GetCoverFromFile, GetCoverFromFile,
GetImageFromURL, GetImageFromURL,
GetMetaFromFile, GetMetaFromFile,
SniffAudioExt, WriteMetaToFlac, WriteMetaToMp3 SniffAudioExt,
WriteMetaToFlac,
WriteMetaToMp3
} from "@/decrypt/utils"; } from "@/decrypt/utils";
import {parseBlob as metaParseBlob} from "music-metadata-browser"; import {parseBlob as metaParseBlob} from "music-metadata-browser";
import {DecryptQMCv2} from "./qmcv2"; import {DecryptQMCv2} from "./qmcv2";
@ -14,133 +15,125 @@ import {DecryptQMCv2} from "./qmcv2";
import iconv from "iconv-lite"; import iconv from "iconv-lite";
import {DecryptResult} from "@/decrypt/entity"; import {DecryptResult} from "@/decrypt/entity";
import {queryAlbumCover, queryKeyInfo, reportKeyUsage} from "@/utils/api"; import {queryAlbumCover} from "@/utils/api";
interface Handler { interface Handler {
ext: string ext: string
version: number version: number
} }
export const HandlerMap: { [key: string]: Handler } = { export const HandlerMap: { [key: string]: Handler } = {
"mgg": {ext: "ogg", version: 2}, "mgg": {ext: "ogg", version: 2},
"mgg1": {ext: "ogg", version: 2}, "mgg1": {ext: "ogg", version: 2},
"mflac": {ext: "flac", version: 2}, "mflac": {ext: "flac", version: 2},
"mflac0": {ext: "flac", version: 2}, "mflac0": {ext: "flac", version: 2},
// qmcflac / qmcogg: // qmcflac / qmcogg:
// 有可能是 v2 加密但混用同一个后缀名。 // 有可能是 v2 加密但混用同一个后缀名。
"qmcflac": {ext: "flac", version: 2}, "qmcflac": {ext: "flac", version: 2},
"qmcogg": {ext: "ogg", version: 2}, "qmcogg": {ext: "ogg", version: 2},
"qmc0": {ext: "mp3", version: 1}, "qmc0": {ext: "mp3", version: 1},
"qmc2": {ext: "ogg", version: 1}, "qmc2": {ext: "ogg", version: 1},
"qmc3": {ext: "mp3", version: 1}, "qmc3": {ext: "mp3", version: 1},
"bkcmp3": {ext: "mp3", version: 1}, "bkcmp3": {ext: "mp3", version: 1},
"bkcflac": {ext: "flac", version: 1}, "bkcflac": {ext: "flac", version: 1},
"tkm": {ext: "m4a", version: 1}, "tkm": {ext: "m4a", version: 1},
"666c6163": {ext: "flac", version: 1}, "666c6163": {ext: "flac", version: 1},
"6d7033": {ext: "mp3", version: 1}, "6d7033": {ext: "mp3", version: 1},
"6f6767": {ext: "ogg", version: 1}, "6f6767": {ext: "ogg", version: 1},
"6d3461": {ext: "m4a", version: 1}, "6d3461": {ext: "m4a", version: 1},
"776176": {ext: "wav", version: 1} "776176": {ext: "wav", version: 1}
}; };
export async function Decrypt(file: Blob, raw_filename: string, raw_ext: string): Promise<DecryptResult> { export async function Decrypt(file: Blob, raw_filename: string, raw_ext: string): Promise<DecryptResult> {
if (!(raw_ext in HandlerMap)) throw `Qmc cannot handle type: ${raw_ext}`; if (!(raw_ext in HandlerMap)) throw `Qmc cannot handle type: ${raw_ext}`;
const handler = HandlerMap[raw_ext]; const handler = HandlerMap[raw_ext];
let { version } = handler; let {version} = handler;
const fileBuffer = await GetArrayBuffer(file); const fileBuffer = await GetArrayBuffer(file);
let musicDecoded: Uint8Array|undefined; let musicDecoded: Uint8Array | undefined;
if (version === 2) { if (version === 2) {
const v2Decrypted = await DecryptQMCv2(fileBuffer); const v2Decrypted = await DecryptQMCv2(fileBuffer);
// 如果 v2 检测失败,降级到 v1 再尝试一次 // 如果 v2 检测失败,降级到 v1 再尝试一次
if (v2Decrypted) { if (v2Decrypted) {
musicDecoded = v2Decrypted; musicDecoded = v2Decrypted;
} else { } else {
version = 1; version = 1;
}
}
if (version === 1) {
const seed = new QmcStaticCipher();
musicDecoded = new Uint8Array(fileBuffer)
seed.decrypt(musicDecoded, 0);
} else if (!musicDecoded) {
throw new Error(`解密失败: ${raw_ext}`);
}
const ext = SniffAudioExt(musicDecoded, handler.ext);
const mime = AudioMimeType[ext];
let musicBlob = new Blob([musicDecoded], {type: mime});
const musicMeta = await metaParseBlob(musicBlob);
for (let metaIdx in musicMeta.native) {
if (!musicMeta.native.hasOwnProperty(metaIdx)) continue
if (musicMeta.native[metaIdx].some(item => item.id === "TCON" && item.value === "(12)")) {
console.warn("try using gbk encoding to decode meta")
musicMeta.common.artist = iconv.decode(new Buffer(musicMeta.common.artist ?? ""), "gbk");
musicMeta.common.title = iconv.decode(new Buffer(musicMeta.common.title ?? ""), "gbk");
musicMeta.common.album = iconv.decode(new Buffer(musicMeta.common.album ?? ""), "gbk");
}
}
const info = GetMetaFromFile(raw_filename, musicMeta.common.title, musicMeta.common.artist)
let imgUrl = GetCoverFromFile(musicMeta);
if (!imgUrl) {
imgUrl = await getCoverImage(info.title, info.artist, musicMeta.common.album);
if (imgUrl) {
const imageInfo = await GetImageFromURL(imgUrl);
if (imageInfo) {
imgUrl = imageInfo.url
try {
const newMeta = {picture: imageInfo.buffer, title: info.title, artists: info.artist?.split(" _ ")}
if (ext === "mp3") {
musicDecoded = WriteMetaToMp3(Buffer.from(musicDecoded), newMeta, musicMeta)
musicBlob = new Blob([musicDecoded], {type: mime});
} else if (ext === 'flac') {
musicDecoded = WriteMetaToFlac(Buffer.from(musicDecoded), newMeta, musicMeta)
musicBlob = new Blob([musicDecoded], {type: mime});
} else {
console.info("writing metadata for " + ext + " is not being supported for now")
}
} catch (e) {
console.warn("Error while appending cover image to file " + e)
} }
}
} }
}
if (version === 1) { return {
const seed = QmcMaskGetDefault(); title: info.title,
musicDecoded = seed.Decrypt(new Uint8Array(fileBuffer)); artist: info.artist,
} else if (!musicDecoded) { ext: ext,
throw new Error(`解密失败: ${raw_ext}`); album: musicMeta.common.album,
} picture: imgUrl,
file: URL.createObjectURL(musicBlob),
const ext = SniffAudioExt(musicDecoded, handler.ext); blob: musicBlob,
const mime = AudioMimeType[ext]; mime: mime
}
let musicBlob = new Blob([musicDecoded], {type: mime});
const musicMeta = await metaParseBlob(musicBlob);
for (let metaIdx in musicMeta.native) {
if (!musicMeta.native.hasOwnProperty(metaIdx)) continue
if (musicMeta.native[metaIdx].some(item => item.id === "TCON" && item.value === "(12)")) {
console.warn("try using gbk encoding to decode meta")
musicMeta.common.artist = iconv.decode(new Buffer(musicMeta.common.artist ?? ""), "gbk");
musicMeta.common.title = iconv.decode(new Buffer(musicMeta.common.title ?? ""), "gbk");
musicMeta.common.album = iconv.decode(new Buffer(musicMeta.common.album ?? ""), "gbk");
}
}
const info = GetMetaFromFile(raw_filename, musicMeta.common.title, musicMeta.common.artist)
let imgUrl = GetCoverFromFile(musicMeta);
if (!imgUrl) {
imgUrl = await getCoverImage(info.title, info.artist, musicMeta.common.album);
if (imgUrl) {
const imageInfo = await GetImageFromURL(imgUrl);
if (imageInfo) {
imgUrl = imageInfo.url
try {
const newMeta = {picture: imageInfo.buffer, title: info.title, artists: info.artist?.split(" _ ")}
if (ext === "mp3") {
musicDecoded = WriteMetaToMp3(Buffer.from(musicDecoded), newMeta, musicMeta)
musicBlob = new Blob([musicDecoded], {type: mime});
} else if (ext === 'flac') {
musicDecoded = WriteMetaToFlac(Buffer.from(musicDecoded), newMeta, musicMeta)
musicBlob = new Blob([musicDecoded], {type: mime});
} else {
console.info("writing metadata for " + ext + " is not being supported for now")
}
} catch (e) {
console.warn("Error while appending cover image to file " + e)
}
}
}
}
return {
title: info.title,
artist: info.artist,
ext: ext,
album: musicMeta.common.album,
picture: imgUrl,
file: URL.createObjectURL(musicBlob),
blob: musicBlob,
mime: mime
}
} }
async function queryKey(keyData: Uint8Array, filename: string, format: string): Promise<QmcMask | undefined> {
try {
const data = await queryKeyInfo(keyData, filename, format)
return new QmcMask(Base64Decode(data.Matrix44));
} catch (e) {
console.warn(e);
}
}
async function getCoverImage(title: string, artist?: string, album?: string): Promise<string> { async function getCoverImage(title: string, artist?: string, album?: string): Promise<string> {
const song_query_url = "https://stats.ixarea.com/apis" + "/music/qq-cover" const song_query_url = "https://stats.ixarea.com/apis" + "/music/qq-cover"
try { try {
const data = await queryAlbumCover(title, artist, album) const data = await queryAlbumCover(title, artist, album)
return `${song_query_url}/${data.Type}/${data.Id}` return `${song_query_url}/${data.Type}/${data.Id}`
} catch (e) { } catch (e) {
console.warn(e); console.warn(e);
} }
return "" return ""
} }

View File

@ -1,98 +0,0 @@
const QMCDefaultMaskMatrix = [
0xde, 0x51, 0xfa, 0xc3, 0x4a, 0xd6, 0xca, 0x90,
0x7e, 0x67, 0x5e, 0xf7, 0xd5, 0x52, 0x84, 0xd8,
0x47, 0x95, 0xbb, 0xa1, 0xaa, 0xc6, 0x66, 0x23,
0x92, 0x62, 0xf3, 0x74, 0xa1, 0x9f, 0xf4, 0xa0,
0x1d, 0x3f, 0x5b, 0xf0, 0x13, 0x0e, 0x09, 0x3d,
0xf9, 0xbc, 0x00, 0x11];
const AllMapping: number[][] = [];
const Mask128to44: number[] = [];
(function () {
for (let i = 0; i < 128; i++) {
let realIdx = (i * i + 27) % 256
if (realIdx in AllMapping) {
AllMapping[realIdx].push(i)
} else {
AllMapping[realIdx] = [i]
}
}
let idx44 = 0
AllMapping.forEach(all128 => {
all128.forEach(_i128 => {
Mask128to44[_i128] = idx44
})
idx44++
})
})();
export class QmcMask {
private readonly Matrix128: number[];
constructor(matrix: number[] | Uint8Array) {
if (matrix instanceof Uint8Array) matrix = Array.from(matrix)
if (matrix.length === 44) {
this.Matrix128 = this._generate128(matrix)
} else if (matrix.length === 128) {
this.Matrix128 = matrix
} else {
throw Error("invalid mask length")
}
}
getMatrix128() {
return this.Matrix128
}
getMatrix44(): number[] {
const matrix44: number[] = []
let idxI44 = 0
AllMapping.forEach(it256 => {
let it256Len = it256.length
for (let i = 1; i < it256Len; i++) {
if (this.Matrix128[it256[0]] !== this.Matrix128[it256[i]]) {
throw "decode mask-128 to mask-44 failed"
}
}
matrix44[idxI44] = this.Matrix128[it256[0]]
idxI44++
})
return matrix44
}
Decrypt(data: Uint8Array) {
if (!this.Matrix128) throw Error("bad call sequence")
let dst = data.slice(0);
let index = -1;
let maskIdx = -1;
for (let cur = 0; cur < data.length; cur++) {
index++;
maskIdx++;
if (index === 0x8000 || (index > 0x8000 && (index + 1) % 0x8000 === 0)) {
index++;
maskIdx++;
}
if (maskIdx >= 128) maskIdx -= 128;
dst[cur] ^= this.Matrix128[maskIdx];
}
return dst;
}
private _generate128(matrix44: number[]): number[] {
const matrix128: number[] = []
let idx44 = 0
AllMapping.forEach(it256 => {
it256.forEach(m => {
matrix128[m] = matrix44[idx44]
})
idx44++
})
return matrix128
}
}
export function QmcMaskGetDefault() {
return new QmcMask(QMCDefaultMaskMatrix)
}

View File

@ -0,0 +1,27 @@
import {QmcStaticCipher} from "@/decrypt/qmc_cipher";
test("static cipher [0x7ff8,0x8000) ", () => {
const expected = new Uint8Array([
0xD8, 0x52, 0xF7, 0x67, 0x90, 0xCA, 0xD6, 0x4A,
0x4A, 0xD6, 0xCA, 0x90, 0x67, 0xF7, 0x52, 0xD8,
])
const c = new QmcStaticCipher()
const buf = new Uint8Array(16)
c.decrypt(buf, 0x7ff8)
expect(buf).toStrictEqual(expected)
})
test("static cipher [0,0x10) ", () => {
const expected = new Uint8Array([
0xC3, 0x4A, 0xD6, 0xCA, 0x90, 0x67, 0xF7, 0x52,
0xD8, 0xA1, 0x66, 0x62, 0x9F, 0x5B, 0x09, 0x00,
])
const c = new QmcStaticCipher()
const buf = new Uint8Array(16)
c.decrypt(buf, 0)
expect(buf).toStrictEqual(expected)
})

53
src/decrypt/qmc_cipher.ts Normal file
View File

@ -0,0 +1,53 @@
const staticCipherBox = new Uint8Array([
0x77, 0x48, 0x32, 0x73, 0xDE, 0xF2, 0xC0, 0xC8, //0x00
0x95, 0xEC, 0x30, 0xB2, 0x51, 0xC3, 0xE1, 0xA0, //0x08
0x9E, 0xE6, 0x9D, 0xCF, 0xFA, 0x7F, 0x14, 0xD1, //0x10
0xCE, 0xB8, 0xDC, 0xC3, 0x4A, 0x67, 0x93, 0xD6, //0x18
0x28, 0xC2, 0x91, 0x70, 0xCA, 0x8D, 0xA2, 0xA4, //0x20
0xF0, 0x08, 0x61, 0x90, 0x7E, 0x6F, 0xA2, 0xE0, //0x28
0xEB, 0xAE, 0x3E, 0xB6, 0x67, 0xC7, 0x92, 0xF4, //0x30
0x91, 0xB5, 0xF6, 0x6C, 0x5E, 0x84, 0x40, 0xF7, //0x38
0xF3, 0x1B, 0x02, 0x7F, 0xD5, 0xAB, 0x41, 0x89, //0x40
0x28, 0xF4, 0x25, 0xCC, 0x52, 0x11, 0xAD, 0x43, //0x48
0x68, 0xA6, 0x41, 0x8B, 0x84, 0xB5, 0xFF, 0x2C, //0x50
0x92, 0x4A, 0x26, 0xD8, 0x47, 0x6A, 0x7C, 0x95, //0x58
0x61, 0xCC, 0xE6, 0xCB, 0xBB, 0x3F, 0x47, 0x58, //0x60
0x89, 0x75, 0xC3, 0x75, 0xA1, 0xD9, 0xAF, 0xCC, //0x68
0x08, 0x73, 0x17, 0xDC, 0xAA, 0x9A, 0xA2, 0x16, //0x70
0x41, 0xD8, 0xA2, 0x06, 0xC6, 0x8B, 0xFC, 0x66, //0x78
0x34, 0x9F, 0xCF, 0x18, 0x23, 0xA0, 0x0A, 0x74, //0x80
0xE7, 0x2B, 0x27, 0x70, 0x92, 0xE9, 0xAF, 0x37, //0x88
0xE6, 0x8C, 0xA7, 0xBC, 0x62, 0x65, 0x9C, 0xC2, //0x90
0x08, 0xC9, 0x88, 0xB3, 0xF3, 0x43, 0xAC, 0x74, //0x98
0x2C, 0x0F, 0xD4, 0xAF, 0xA1, 0xC3, 0x01, 0x64, //0xA0
0x95, 0x4E, 0x48, 0x9F, 0xF4, 0x35, 0x78, 0x95, //0xA8
0x7A, 0x39, 0xD6, 0x6A, 0xA0, 0x6D, 0x40, 0xE8, //0xB0
0x4F, 0xA8, 0xEF, 0x11, 0x1D, 0xF3, 0x1B, 0x3F, //0xB8
0x3F, 0x07, 0xDD, 0x6F, 0x5B, 0x19, 0x30, 0x19, //0xC0
0xFB, 0xEF, 0x0E, 0x37, 0xF0, 0x0E, 0xCD, 0x16, //0xC8
0x49, 0xFE, 0x53, 0x47, 0x13, 0x1A, 0xBD, 0xA4, //0xD0
0xF1, 0x40, 0x19, 0x60, 0x0E, 0xED, 0x68, 0x09, //0xD8
0x06, 0x5F, 0x4D, 0xCF, 0x3D, 0x1A, 0xFE, 0x20, //0xE0
0x77, 0xE4, 0xD9, 0xDA, 0xF9, 0xA4, 0x2B, 0x76, //0xE8
0x1C, 0x71, 0xDB, 0x00, 0xBC, 0xFD, 0x0C, 0x6C, //0xF0
0xA5, 0x47, 0xF7, 0xF6, 0x00, 0x79, 0x4A, 0x11, //0xF8
])
interface streamCipher {
decrypt(buf: Uint8Array, offset: number): void
}
export class QmcStaticCipher implements streamCipher {
public getMask(offset: number) {
if (offset > 0x7FFF) offset %= 0x7FFF
return staticCipherBox[(offset * offset + 27) & 0xff]
}
public decrypt(buf: Uint8Array, offset: number) {
for (let i = 0; i < buf.length; i++) {
buf[i] ^= this.getMask(offset + i)
}
}
}

View File

@ -27,7 +27,6 @@ function MergeUint8Array(array: Uint8Array[]): Uint8Array {
* *
* Uint8Array * Uint8Array
* @param {ArrayBuffer} mggBlob Blob * @param {ArrayBuffer} mggBlob Blob
* @param {string} name
* @return {Promise<Uint8Array|false>} * @return {Promise<Uint8Array|false>}
*/ */
export async function DecryptQMCv2(mggBlob: ArrayBuffer) { export async function DecryptQMCv2(mggBlob: ArrayBuffer) {