init: dec-music 项目初始化
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
package qmc
|
||||
|
||||
import "errors"
|
||||
|
||||
type mapCipher struct {
|
||||
key []byte
|
||||
box []byte
|
||||
size int
|
||||
}
|
||||
|
||||
func newMapCipher(key []byte) (*mapCipher, error) {
|
||||
if len(key) == 0 {
|
||||
return nil, errors.New("qmc/cipher_map: invalid key size")
|
||||
}
|
||||
c := &mapCipher{key: key, size: len(key)}
|
||||
c.box = make([]byte, c.size)
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *mapCipher) getMask(offset int) byte {
|
||||
if offset > 0x7FFF {
|
||||
offset %= 0x7FFF
|
||||
}
|
||||
idx := (offset*offset + 71214) % c.size
|
||||
return c.rotate(c.key[idx], byte(idx)&0x7)
|
||||
}
|
||||
|
||||
func (c *mapCipher) rotate(value byte, bits byte) byte {
|
||||
rotate := (bits + 4) % 8
|
||||
left := value << rotate
|
||||
right := value >> rotate
|
||||
return left | right
|
||||
}
|
||||
|
||||
func (c *mapCipher) Decrypt(buf []byte, offset int) {
|
||||
for i := 0; i < len(buf); i++ {
|
||||
buf[i] ^= c.getMask(offset + i)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package qmc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func loadTestDataMapCipher(name string) ([]byte, []byte, []byte, error) {
|
||||
key, err := os.ReadFile(fmt.Sprintf("./testdata/%s_key.bin", name))
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
raw, err := os.ReadFile(fmt.Sprintf("./testdata/%s_raw.bin", name))
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
target, err := os.ReadFile(fmt.Sprintf("./testdata/%s_target.bin", name))
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
return key, raw, target, nil
|
||||
}
|
||||
func Test_mapCipher_Decrypt(t *testing.T) {
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
wantErr bool
|
||||
}{
|
||||
{"mflac_map", false},
|
||||
{"mgg_map", false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
key, raw, target, err := loadTestDataMapCipher(tt.name)
|
||||
if err != nil {
|
||||
t.Fatalf("load testing data failed: %s", err)
|
||||
}
|
||||
c, err := newMapCipher(key)
|
||||
if err != nil {
|
||||
t.Errorf("init mapCipher failed: %s", err)
|
||||
return
|
||||
}
|
||||
c.Decrypt(raw, 0)
|
||||
if !reflect.DeepEqual(raw, target) {
|
||||
t.Error("overall")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package qmc
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
// A rc4Cipher is an instance of RC4 using a particular key.
|
||||
type rc4Cipher struct {
|
||||
box []byte
|
||||
key []byte
|
||||
hash uint32
|
||||
n int
|
||||
}
|
||||
|
||||
// newRC4Cipher creates and returns a new rc4Cipher. The key argument should be the
|
||||
// RC4 key, at least 1 byte and at most 256 bytes.
|
||||
func newRC4Cipher(key []byte) (*rc4Cipher, error) {
|
||||
n := len(key)
|
||||
if n == 0 {
|
||||
return nil, errors.New("qmc/cipher_rc4: invalid key size")
|
||||
}
|
||||
|
||||
var c = rc4Cipher{key: key, n: n}
|
||||
c.box = make([]byte, n)
|
||||
|
||||
for i := 0; i < n; i++ {
|
||||
c.box[i] = byte(i)
|
||||
}
|
||||
|
||||
var j = 0
|
||||
for i := 0; i < n; i++ {
|
||||
j = (j + int(c.box[i]) + int(key[i%n])) % n
|
||||
c.box[i], c.box[j] = c.box[j], c.box[i]
|
||||
}
|
||||
c.getHashBase()
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (c *rc4Cipher) getHashBase() {
|
||||
c.hash = 1
|
||||
for i := 0; i < c.n; i++ {
|
||||
v := uint32(c.key[i])
|
||||
if v == 0 {
|
||||
continue
|
||||
}
|
||||
nextHash := c.hash * v
|
||||
if nextHash == 0 || nextHash <= c.hash {
|
||||
break
|
||||
}
|
||||
c.hash = nextHash
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
rc4SegmentSize = 5120
|
||||
rc4FirstSegmentSize = 128
|
||||
)
|
||||
|
||||
func (c *rc4Cipher) Decrypt(src []byte, offset int) {
|
||||
toProcess := len(src)
|
||||
processed := 0
|
||||
markProcess := func(p int) (finished bool) {
|
||||
offset += p
|
||||
toProcess -= p
|
||||
processed += p
|
||||
return toProcess == 0
|
||||
}
|
||||
|
||||
if offset < rc4FirstSegmentSize {
|
||||
blockSize := toProcess
|
||||
if blockSize > rc4FirstSegmentSize-offset {
|
||||
blockSize = rc4FirstSegmentSize - offset
|
||||
}
|
||||
c.encFirstSegment(src[:blockSize], offset)
|
||||
if markProcess(blockSize) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if offset%rc4SegmentSize != 0 {
|
||||
blockSize := toProcess
|
||||
if blockSize > rc4SegmentSize-offset%rc4SegmentSize {
|
||||
blockSize = rc4SegmentSize - offset%rc4SegmentSize
|
||||
}
|
||||
c.encASegment(src[processed:processed+blockSize], offset)
|
||||
if markProcess(blockSize) {
|
||||
return
|
||||
}
|
||||
}
|
||||
for toProcess > rc4SegmentSize {
|
||||
c.encASegment(src[processed:processed+rc4SegmentSize], offset)
|
||||
markProcess(rc4SegmentSize)
|
||||
}
|
||||
|
||||
if toProcess > 0 {
|
||||
c.encASegment(src[processed:], offset)
|
||||
}
|
||||
}
|
||||
func (c *rc4Cipher) encFirstSegment(buf []byte, offset int) {
|
||||
for i := 0; i < len(buf); i++ {
|
||||
buf[i] ^= c.key[c.getSegmentSkip(offset+i)]
|
||||
}
|
||||
}
|
||||
|
||||
func (c *rc4Cipher) encASegment(buf []byte, offset int) {
|
||||
box := make([]byte, c.n)
|
||||
copy(box, c.box)
|
||||
j, k := 0, 0
|
||||
|
||||
skipLen := (offset % rc4SegmentSize) + c.getSegmentSkip(offset/rc4SegmentSize)
|
||||
for i := -skipLen; i < len(buf); i++ {
|
||||
j = (j + 1) % c.n
|
||||
k = (int(box[j]) + k) % c.n
|
||||
box[j], box[k] = box[k], box[j]
|
||||
if i >= 0 {
|
||||
buf[i] ^= box[(int(box[j])+int(box[k]))%c.n]
|
||||
}
|
||||
}
|
||||
}
|
||||
func (c *rc4Cipher) getSegmentSkip(id int) int {
|
||||
seed := int(c.key[id%c.n])
|
||||
idx := int64(float64(c.hash) / float64((id+1)*seed) * 100.0)
|
||||
return int(idx % int64(c.n))
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package qmc
|
||||
|
||||
import (
|
||||
"os"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func loadTestRC4CipherData(name string) ([]byte, []byte, []byte, error) {
|
||||
prefix := "./testdata/" + name
|
||||
key, err := os.ReadFile(prefix + "_key.bin")
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
raw, err := os.ReadFile(prefix + "_raw.bin")
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
target, err := os.ReadFile(prefix + "_target.bin")
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
|
||||
return key, raw, target, nil
|
||||
}
|
||||
func Test_rc4Cipher_Decrypt(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
wantErr bool
|
||||
}{
|
||||
{"mflac0_rc4", false},
|
||||
{"mflac_rc4", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
key, raw, target, err := loadTestRC4CipherData(tt.name)
|
||||
if err != nil {
|
||||
t.Fatalf("load testing data failed: %s", err)
|
||||
}
|
||||
c, err := newRC4Cipher(key)
|
||||
if err != nil {
|
||||
t.Errorf("init rc4Cipher failed: %s", err)
|
||||
return
|
||||
}
|
||||
c.Decrypt(raw, 0)
|
||||
if !reflect.DeepEqual(raw, target) {
|
||||
t.Error("overall")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
func BenchmarkRc4Cipher_Decrypt(b *testing.B) {
|
||||
key, raw, _, err := loadTestRC4CipherData("mflac0_rc4")
|
||||
if err != nil {
|
||||
b.Fatalf("load testing data failed: %s", err)
|
||||
}
|
||||
c, err := newRC4Cipher(key)
|
||||
if err != nil {
|
||||
b.Errorf("init rc4Cipher failed: %s", err)
|
||||
return
|
||||
}
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
c.Decrypt(raw, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_rc4Cipher_encFirstSegment(t *testing.T) {
|
||||
key, raw, target, err := loadTestRC4CipherData("mflac0_rc4")
|
||||
if err != nil {
|
||||
t.Fatalf("load testing data failed: %s", err)
|
||||
}
|
||||
t.Run("first-block(0~128)", func(t *testing.T) {
|
||||
c, err := newRC4Cipher(key)
|
||||
if err != nil {
|
||||
t.Errorf("init rc4Cipher failed: %s", err)
|
||||
return
|
||||
}
|
||||
c.Decrypt(raw[:128], 0)
|
||||
if !reflect.DeepEqual(raw[:128], target[:128]) {
|
||||
t.Error("first-block(0~128)")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func Test_rc4Cipher_encASegment(t *testing.T) {
|
||||
key, raw, target, err := loadTestRC4CipherData("mflac0_rc4")
|
||||
if err != nil {
|
||||
t.Fatalf("load testing data failed: %s", err)
|
||||
}
|
||||
|
||||
t.Run("align-block(128~5120)", func(t *testing.T) {
|
||||
c, err := newRC4Cipher(key)
|
||||
if err != nil {
|
||||
t.Errorf("init rc4Cipher failed: %s", err)
|
||||
return
|
||||
}
|
||||
c.Decrypt(raw[128:5120], 128)
|
||||
if !reflect.DeepEqual(raw[128:5120], target[128:5120]) {
|
||||
t.Error("align-block(128~5120)")
|
||||
}
|
||||
})
|
||||
t.Run("simple-block(5120~10240)", func(t *testing.T) {
|
||||
c, err := newRC4Cipher(key)
|
||||
if err != nil {
|
||||
t.Errorf("init rc4Cipher failed: %s", err)
|
||||
return
|
||||
}
|
||||
c.Decrypt(raw[5120:10240], 5120)
|
||||
if !reflect.DeepEqual(raw[5120:10240], target[5120:10240]) {
|
||||
t.Error("align-block(128~5120)")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package qmc
|
||||
|
||||
func newStaticCipher() *staticCipher {
|
||||
return &defaultStaticCipher
|
||||
}
|
||||
|
||||
var defaultStaticCipher = staticCipher{}
|
||||
|
||||
type staticCipher struct{}
|
||||
|
||||
func (c *staticCipher) Decrypt(buf []byte, offset int) {
|
||||
for i := 0; i < len(buf); i++ {
|
||||
buf[i] ^= c.getMask(offset + i)
|
||||
}
|
||||
}
|
||||
func (c *staticCipher) getMask(offset int) byte {
|
||||
if offset > 0x7FFF {
|
||||
offset %= 0x7FFF
|
||||
}
|
||||
idx := (offset*offset + 27) & 0xff
|
||||
return staticCipherBox[idx]
|
||||
}
|
||||
|
||||
var staticCipherBox = [...]byte{
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package qmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"jsuse.com/dev/dec-music/internal/tea"
|
||||
)
|
||||
|
||||
func simpleMakeKey(salt byte, length int) []byte {
|
||||
keyBuf := make([]byte, length)
|
||||
for i := 0; i < length; i++ {
|
||||
tmp := math.Tan(float64(salt) + float64(i)*0.1)
|
||||
keyBuf[i] = byte(math.Abs(tmp) * 100.0)
|
||||
}
|
||||
return keyBuf
|
||||
}
|
||||
|
||||
const rawKeyPrefixV2 = "QQMusic EncV2,Key:"
|
||||
|
||||
func deriveKey(rawKey []byte) ([]byte, error) {
|
||||
rawKeyDec := make([]byte, base64.StdEncoding.DecodedLen(len(rawKey)))
|
||||
n, err := base64.StdEncoding.Decode(rawKeyDec, rawKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rawKeyDec = rawKeyDec[:n]
|
||||
|
||||
if bytes.HasPrefix(rawKeyDec, []byte(rawKeyPrefixV2)) {
|
||||
rawKeyDec, err = deriveKeyV2(bytes.TrimPrefix(rawKeyDec, []byte(rawKeyPrefixV2)))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("deriveKeyV2 failed: %w", err)
|
||||
}
|
||||
}
|
||||
return deriveKeyV1(rawKeyDec)
|
||||
}
|
||||
|
||||
func deriveKeyV1(rawKeyDec []byte) ([]byte, error) {
|
||||
if len(rawKeyDec) < 16 {
|
||||
return nil, errors.New("key length is too short")
|
||||
}
|
||||
|
||||
simpleKey := simpleMakeKey(106, 8)
|
||||
teaKey := make([]byte, 16)
|
||||
for i := 0; i < 8; i++ {
|
||||
teaKey[i<<1] = simpleKey[i]
|
||||
teaKey[i<<1+1] = rawKeyDec[i]
|
||||
}
|
||||
|
||||
rs, err := decryptTencentTea(rawKeyDec[8:], teaKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return append(rawKeyDec[:8], rs...), nil
|
||||
}
|
||||
|
||||
var (
|
||||
deriveV2Key1 = []byte{
|
||||
0x33, 0x38, 0x36, 0x5A, 0x4A, 0x59, 0x21, 0x40,
|
||||
0x23, 0x2A, 0x24, 0x25, 0x5E, 0x26, 0x29, 0x28,
|
||||
}
|
||||
|
||||
deriveV2Key2 = []byte{
|
||||
0x2A, 0x2A, 0x23, 0x21, 0x28, 0x23, 0x24, 0x25,
|
||||
0x26, 0x5E, 0x61, 0x31, 0x63, 0x5A, 0x2C, 0x54,
|
||||
}
|
||||
)
|
||||
|
||||
func deriveKeyV2(raw []byte) ([]byte, error) {
|
||||
buf, err := decryptTencentTea(raw, deriveV2Key1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
buf, err = decryptTencentTea(buf, deriveV2Key2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
n, err := base64.StdEncoding.Decode(buf, buf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf[:n], nil
|
||||
}
|
||||
|
||||
func decryptTencentTea(inBuf []byte, key []byte) ([]byte, error) {
|
||||
const saltLen = 2
|
||||
const zeroLen = 7
|
||||
if len(inBuf)%8 != 0 {
|
||||
return nil, errors.New("inBuf size not a multiple of the block size")
|
||||
}
|
||||
if len(inBuf) < 16 {
|
||||
return nil, errors.New("inBuf size too small")
|
||||
}
|
||||
|
||||
blk, err := tea.NewCipherWithRounds(key, 32)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
destBuf := make([]byte, 8)
|
||||
blk.Decrypt(destBuf, inBuf)
|
||||
padLen := int(destBuf[0] & 0x7)
|
||||
outLen := len(inBuf) - 1 - padLen - saltLen - zeroLen
|
||||
|
||||
out := make([]byte, outLen)
|
||||
|
||||
ivPrev := make([]byte, 8)
|
||||
ivCur := inBuf[:8]
|
||||
|
||||
inBufPos := 8
|
||||
|
||||
destIdx := 1 + padLen
|
||||
cryptBlock := func() {
|
||||
ivPrev = ivCur
|
||||
ivCur = inBuf[inBufPos : inBufPos+8]
|
||||
|
||||
xor8Bytes(destBuf, destBuf, inBuf[inBufPos:inBufPos+8])
|
||||
blk.Decrypt(destBuf, destBuf)
|
||||
|
||||
inBufPos += 8
|
||||
destIdx = 0
|
||||
}
|
||||
for i := 1; i <= saltLen; {
|
||||
if destIdx < 8 {
|
||||
destIdx++
|
||||
i++
|
||||
} else if destIdx == 8 {
|
||||
cryptBlock()
|
||||
}
|
||||
}
|
||||
|
||||
outPos := 0
|
||||
for outPos < outLen {
|
||||
if destIdx < 8 {
|
||||
out[outPos] = destBuf[destIdx] ^ ivPrev[destIdx]
|
||||
destIdx++
|
||||
outPos++
|
||||
} else if destIdx == 8 {
|
||||
cryptBlock()
|
||||
}
|
||||
}
|
||||
|
||||
for i := 1; i <= zeroLen; i++ {
|
||||
if destBuf[destIdx] != ivPrev[destIdx] {
|
||||
return nil, errors.New("zero check failed")
|
||||
}
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func xor8Bytes(dst, a, b []byte) {
|
||||
for i := 0; i < 8; i++ {
|
||||
dst[i] = a[i] ^ b[i]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package qmc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSimpleMakeKey(t *testing.T) {
|
||||
expect := []byte{0x69, 0x56, 0x46, 0x38, 0x2b, 0x20, 0x15, 0x0b}
|
||||
t.Run("106,8", func(t *testing.T) {
|
||||
if got := simpleMakeKey(106, 8); !reflect.DeepEqual(got, expect) {
|
||||
t.Errorf("simpleMakeKey() = %v, want %v", got, expect)
|
||||
}
|
||||
})
|
||||
}
|
||||
func loadDecryptKeyData(name string) ([]byte, []byte, error) {
|
||||
keyRaw, err := os.ReadFile(fmt.Sprintf("./testdata/%s_key_raw.bin", name))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
keyDec, err := os.ReadFile(fmt.Sprintf("./testdata/%s_key.bin", name))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return keyRaw, keyDec, nil
|
||||
}
|
||||
func TestDecryptKey(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
filename string
|
||||
wantErr bool
|
||||
}{
|
||||
{"mflac0_rc4(512)", "mflac0_rc4", false},
|
||||
{"mflac_map(256)", "mflac_map", false},
|
||||
{"mflac_rc4(256)", "mflac_rc4", false},
|
||||
{"mgg_map(256)", "mgg_map", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
raw, want, err := loadDecryptKeyData(tt.filename)
|
||||
if err != nil {
|
||||
t.Fatalf("load test data failed: %s", err)
|
||||
}
|
||||
got, err := deriveKey(raw)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("deriveKey() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("deriveKey() got = %v..., want %v...",
|
||||
string(got[:32]), string(want[:32]))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package qmc
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"jsuse.com/dev/dec-music/log"
|
||||
"jsuse.com/dev/dec-music/mmkv"
|
||||
)
|
||||
|
||||
var streamKeyVault mmkv.Vault
|
||||
|
||||
func readKeyFromMMKV(file string, logger *log.Logger) ([]byte, error) {
|
||||
if file == "" {
|
||||
return nil, errors.New("file path is required while reading key from mmkv")
|
||||
}
|
||||
if runtime.GOOS != "darwin" {
|
||||
return nil, errors.New("mmkv vault not supported on this platform")
|
||||
}
|
||||
|
||||
if streamKeyVault == nil {
|
||||
mmkvDir, err := getRelativeMMKVDir(file)
|
||||
if err != nil {
|
||||
mmkvDir, err = getDefaultMMKVDir()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mmkv key vault not found: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
mgr, err := mmkv.NewManager(mmkvDir)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("init mmkv manager: %w", err)
|
||||
}
|
||||
|
||||
streamKeyVault, err = mgr.OpenVault("MMKVStreamEncryptId")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open mmkv vault: %w", err)
|
||||
}
|
||||
|
||||
if logger != nil {
|
||||
logger.Debug("mmkv vault opened, keys:", len(streamKeyVault.Keys()))
|
||||
}
|
||||
}
|
||||
|
||||
_, partName := filepath.Split(file)
|
||||
partName = normalizeUnicode(partName)
|
||||
|
||||
buf, err := streamKeyVault.GetBytes(file)
|
||||
if buf == nil {
|
||||
filePaths := streamKeyVault.Keys()
|
||||
fileNames := make([]string, len(filePaths))
|
||||
for i, filePath := range filePaths {
|
||||
_, name := filepath.Split(filePath)
|
||||
fileNames[i] = normalizeUnicode(name)
|
||||
}
|
||||
|
||||
for i, key := range fileNames {
|
||||
if key != partName {
|
||||
continue
|
||||
}
|
||||
buf, err = streamKeyVault.GetBytes(filePaths[i])
|
||||
if err != nil && logger != nil {
|
||||
logger.Warn("read key from mmkv", filePaths[i], err)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if len(buf) == 0 {
|
||||
return nil, errors.New("key not found in mmkv vault")
|
||||
}
|
||||
return deriveKey(buf)
|
||||
}
|
||||
|
||||
// OpenMMKVCLI opens a QQ Music MMKV vault (used by the CLI).
|
||||
func OpenMMKVCLI(mmkvPath, key string, logger *log.Logger) error {
|
||||
return openMMKV(mmkvPath, key, logger)
|
||||
}
|
||||
|
||||
func openMMKV(mmkvPath, key string, logger *log.Logger) error {
|
||||
filePath, fileName := filepath.Split(mmkvPath)
|
||||
mgr, err := mmkv.NewManager(filepath.Dir(filePath))
|
||||
if err != nil {
|
||||
return fmt.Errorf("init mmkv manager: %w", err)
|
||||
}
|
||||
|
||||
streamKeyVault, err = mgr.OpenVaultCrypto(fileName, key)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open mmkv vault: %w", err)
|
||||
}
|
||||
if logger != nil {
|
||||
logger.Debug("mmkv vault opened, keys:", len(streamKeyVault.Keys()))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readKeyFromMMKVCustom(mid string) ([]byte, error) {
|
||||
if streamKeyVault == nil {
|
||||
return nil, fmt.Errorf("mmkv vault not loaded")
|
||||
}
|
||||
eKey, err := streamKeyVault.GetBytes(mid)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get eKey error: %w", err)
|
||||
}
|
||||
return deriveKey(eKey)
|
||||
}
|
||||
|
||||
func getRelativeMMKVDir(file string) (string, error) {
|
||||
mmkvDir := filepath.Join(filepath.Dir(file), "../mmkv")
|
||||
if _, err := os.Stat(mmkvDir); err != nil {
|
||||
return "", err
|
||||
}
|
||||
keyFile := filepath.Join(mmkvDir, "MMKVStreamEncryptId")
|
||||
if _, err := os.Stat(keyFile); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return mmkvDir, nil
|
||||
}
|
||||
|
||||
func getDefaultMMKVDir() (string, error) {
|
||||
homeDir, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
mmkvDir := filepath.Join(
|
||||
homeDir,
|
||||
"Library/Containers/com.tencent.QQMusicMac/Data",
|
||||
"Library/Application Support/QQMusicMac/mmkv",
|
||||
)
|
||||
if _, err := os.Stat(mmkvDir); err != nil {
|
||||
return "", err
|
||||
}
|
||||
keyFile := filepath.Join(mmkvDir, "MMKVStreamEncryptId")
|
||||
if _, err := os.Stat(keyFile); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return mmkvDir, nil
|
||||
}
|
||||
|
||||
// normalizeUnicode applies a simple NFC-like fix for macOS decomposed filenames.
|
||||
func normalizeUnicode(str string) string {
|
||||
if utf8.ValidString(str) && !strings.ContainsRune(str, '\u0300') {
|
||||
return str
|
||||
}
|
||||
var b strings.Builder
|
||||
for _, r := range str {
|
||||
if r >= 0x0300 && r <= 0x036F {
|
||||
continue
|
||||
}
|
||||
b.WriteRune(r)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package qmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"jsuse.com/dev/dec-music/decrypt"
|
||||
"jsuse.com/dev/dec-music/internal/sniff"
|
||||
"jsuse.com/dev/dec-music/log"
|
||||
)
|
||||
|
||||
type decoder struct {
|
||||
raw io.ReadSeeker
|
||||
params *decrypt.DecoderParams
|
||||
|
||||
audio io.Reader
|
||||
audioLen int
|
||||
offset int
|
||||
|
||||
decodedKey []byte
|
||||
cipher decrypt.StreamDecoder
|
||||
|
||||
logger *log.Logger
|
||||
}
|
||||
|
||||
func newDecoder(p *decrypt.DecoderParams) decrypt.Decoder {
|
||||
return &decoder{raw: p.Reader, params: p, logger: p.Logger}
|
||||
}
|
||||
|
||||
func (d *decoder) Read(p []byte) (int, error) {
|
||||
n, err := d.audio.Read(p)
|
||||
if n > 0 {
|
||||
d.cipher.Decrypt(p[:n], d.offset)
|
||||
d.offset += n
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (d *decoder) Validate() error {
|
||||
if err := d.searchKey(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var err error
|
||||
if len(d.decodedKey) > 300 {
|
||||
d.cipher, err = newRC4Cipher(d.decodedKey)
|
||||
} else if len(d.decodedKey) != 0 {
|
||||
d.cipher, err = newMapCipher(d.decodedKey)
|
||||
} else {
|
||||
d.cipher = newStaticCipher()
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := d.validateDecode(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := d.raw.Seek(0, io.SeekStart); err != nil {
|
||||
return err
|
||||
}
|
||||
d.audio = io.LimitReader(d.raw, int64(d.audioLen))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *decoder) validateDecode() error {
|
||||
if _, err := d.raw.Seek(0, io.SeekStart); err != nil {
|
||||
return fmt.Errorf("qmc seek to start: %w", err)
|
||||
}
|
||||
|
||||
buf := make([]byte, 64)
|
||||
if _, err := io.ReadFull(d.raw, buf); err != nil {
|
||||
return fmt.Errorf("qmc read header: %w", err)
|
||||
}
|
||||
|
||||
d.cipher.Decrypt(buf, 0)
|
||||
if _, ok := sniff.AudioExtension(buf); !ok {
|
||||
return errors.New("qmc: detect file type failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *decoder) searchKey() (err error) {
|
||||
fileSizeM4, err := d.raw.Seek(-4, io.SeekEnd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fileSize := int(fileSizeM4) + 4
|
||||
|
||||
if runtime.GOOS == "darwin" && !strings.HasPrefix(d.params.Extension, ".qmc") {
|
||||
d.decodedKey, err = readKeyFromMMKV(d.params.FilePath, d.logger)
|
||||
if err == nil {
|
||||
d.audioLen = fileSize
|
||||
return nil
|
||||
}
|
||||
if d.logger != nil {
|
||||
d.logger.Warn("read key from mmkv failed:", err)
|
||||
}
|
||||
}
|
||||
|
||||
suffixBuf := make([]byte, 4)
|
||||
if _, err := io.ReadFull(d.raw, suffixBuf); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch string(suffixBuf) {
|
||||
case "QTag":
|
||||
return d.readRawMetaQTag()
|
||||
case "STag":
|
||||
return errors.New("qmc: file with 'STag' suffix doesn't contains media key")
|
||||
case "cex\x00":
|
||||
footer, err := newMusicExTag(d.raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.audioLen = fileSize - int(footer.tagSize)
|
||||
d.decodedKey, err = readKeyFromMMKVCustom(footer.mediaFileName)
|
||||
return err
|
||||
default:
|
||||
size := binary.LittleEndian.Uint32(suffixBuf)
|
||||
if size <= 0xFFFF && size != 0 {
|
||||
return d.readRawKey(int64(size))
|
||||
}
|
||||
d.audioLen = fileSize
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (d *decoder) readRawKey(rawKeyLen int64) error {
|
||||
audioLen, err := d.raw.Seek(-(4 + rawKeyLen), io.SeekEnd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.audioLen = int(audioLen)
|
||||
|
||||
rawKeyData, err := io.ReadAll(io.LimitReader(d.raw, rawKeyLen))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rawKeyData = bytes.TrimRight(rawKeyData, "\x00")
|
||||
|
||||
d.decodedKey, err = deriveKey(rawKeyData)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *decoder) readRawMetaQTag() error {
|
||||
if _, err := d.raw.Seek(-8, io.SeekEnd); err != nil {
|
||||
return err
|
||||
}
|
||||
buf, err := io.ReadAll(io.LimitReader(d.raw, 4))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rawMetaLen := int64(binary.BigEndian.Uint32(buf))
|
||||
|
||||
audioLen, err := d.raw.Seek(-(8 + rawMetaLen), io.SeekEnd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.audioLen = int(audioLen)
|
||||
rawMetaData, err := io.ReadAll(io.LimitReader(d.raw, rawMetaLen))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
items := strings.Split(string(rawMetaData), ",")
|
||||
if len(items) != 3 {
|
||||
return errors.New("invalid raw meta data")
|
||||
}
|
||||
|
||||
d.decodedKey, err = deriveKey([]byte(items[0]))
|
||||
return err
|
||||
}
|
||||
|
||||
func init() {
|
||||
supportedExts := []string{
|
||||
"qmc0", "qmc3", "qmc2", "qmc4", "qmc6", "qmc8",
|
||||
"qmcflac", "qmcogg", "tkm",
|
||||
"bkcmp3", "bkcm4a", "bkcflac", "bkcwav", "bkcape", "bkcogg", "bkcwma",
|
||||
"666c6163", "6d7033", "6f6767", "6d3461", "776176", "mmp4",
|
||||
}
|
||||
for _, ext := range supportedExts {
|
||||
decrypt.RegisterDecoder(ext, false , newDecoder)
|
||||
}
|
||||
|
||||
for _, ext := range []string{"mgg", "mflac"} {
|
||||
decrypt.RegisterDecoder(ext, false , newDecoder)
|
||||
for _, suffix := range []string{"0", "1", "a", "h", "l"} {
|
||||
decrypt.RegisterDecoder(ext+suffix, false , newDecoder)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package qmc
|
||||
|
||||
import (
|
||||
bytes "bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type musicExTagV1 struct {
|
||||
songID uint32
|
||||
unknown1 uint32
|
||||
unknown2 uint32
|
||||
mediaID string
|
||||
mediaFileName string
|
||||
unknown3 uint32
|
||||
tagSize uint32
|
||||
tagVersion uint32
|
||||
tagMagic []byte
|
||||
}
|
||||
|
||||
func newMusicExTag(f io.ReadSeeker) (*musicExTagV1, error) {
|
||||
_, err := f.Seek(-16, io.SeekEnd)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("musicex seek error: %w", err)
|
||||
}
|
||||
|
||||
buffer := make([]byte, 16)
|
||||
bytesRead, err := f.Read(buffer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get musicex error: %w", err)
|
||||
}
|
||||
if bytesRead != 16 {
|
||||
return nil, fmt.Errorf("MusicExV1: read %d bytes (expected %d)", bytesRead, 16)
|
||||
}
|
||||
|
||||
tag := &musicExTagV1{
|
||||
tagSize: binary.LittleEndian.Uint32(buffer[0x00:0x04]),
|
||||
tagVersion: binary.LittleEndian.Uint32(buffer[0x04:0x08]),
|
||||
tagMagic: buffer[0x08:0x10],
|
||||
}
|
||||
|
||||
if !bytes.Equal(tag.tagMagic, []byte("musicex\x00")) {
|
||||
return nil, errors.New("MusicEx magic mismatch")
|
||||
}
|
||||
if tag.tagVersion != 1 {
|
||||
return nil, fmt.Errorf("unsupported musicex tag version: %d", tag.tagVersion)
|
||||
}
|
||||
|
||||
if tag.tagSize < 0xC0 {
|
||||
return nil, fmt.Errorf("unsupported musicex tag size: 0x%x", tag.tagSize)
|
||||
}
|
||||
|
||||
buffer = make([]byte, tag.tagSize)
|
||||
bytesRead, err = f.Read(buffer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if uint32(bytesRead) != tag.tagSize {
|
||||
return nil, fmt.Errorf("MusicExV1: read %d bytes (expected %d)", bytesRead, tag.tagSize)
|
||||
}
|
||||
|
||||
tag.songID = binary.LittleEndian.Uint32(buffer[0x00:0x04])
|
||||
tag.unknown1 = binary.LittleEndian.Uint32(buffer[0x04:0x08])
|
||||
tag.unknown2 = binary.LittleEndian.Uint32(buffer[0x08:0x0C])
|
||||
tag.mediaID = readUnicodeTagName(buffer[0x0C:], 30*2)
|
||||
tag.mediaFileName = readUnicodeTagName(buffer[0x48:], 50*2)
|
||||
tag.unknown3 = binary.LittleEndian.Uint32(buffer[0xAC:0xB0])
|
||||
return tag, nil
|
||||
}
|
||||
|
||||
// readUnicodeTagName reads a buffer to maxLen.
|
||||
// reconstruct text by skipping alternate char (ascii chars encoded in UTF-16-LE),
|
||||
// until finding a zero or reaching maxLen.
|
||||
func readUnicodeTagName(buffer []byte, maxLen int) string {
|
||||
builder := strings.Builder{}
|
||||
|
||||
for i := 0; i < maxLen; i += 2 {
|
||||
chr := buffer[i]
|
||||
if chr != 0 {
|
||||
builder.WriteByte(chr)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return builder.String()
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package qmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"jsuse.com/dev/dec-music/decrypt"
|
||||
)
|
||||
|
||||
func loadTestDataQmcDecoder(filename string) ([]byte, []byte, error) {
|
||||
encBody, err := os.ReadFile(fmt.Sprintf("./testdata/%s_raw.bin", filename))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
encSuffix, err := os.ReadFile(fmt.Sprintf("./testdata/%s_suffix.bin", filename))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
target, err := os.ReadFile(fmt.Sprintf("./testdata/%s_target.bin", filename))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return bytes.Join([][]byte{encBody, encSuffix}, nil), target, nil
|
||||
|
||||
}
|
||||
func TestMflac0Decoder_Read(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
fileExt string
|
||||
wantErr bool
|
||||
}{
|
||||
{"mflac0_rc4", ".mflac0", false},
|
||||
{"mflac_rc4", ".mflac", false},
|
||||
{"mflac_map", ".mflac", false},
|
||||
{"mgg_map", ".mgg", false},
|
||||
{"qmc0_static", ".qmc0", false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
raw, target, err := loadTestDataQmcDecoder(tt.name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
d := newDecoder(&decrypt.DecoderParams{
|
||||
Reader: bytes.NewReader(raw),
|
||||
Extension: tt.fileExt,
|
||||
})
|
||||
if err := d.Validate(); err != nil {
|
||||
t.Errorf("validate file error = %v", err)
|
||||
}
|
||||
|
||||
buf := make([]byte, len(target))
|
||||
if _, err := io.ReadFull(d, buf); err != nil {
|
||||
t.Errorf("read bytes from decoder error = %v", err)
|
||||
return
|
||||
}
|
||||
if !reflect.DeepEqual(buf, target) {
|
||||
t.Errorf("Decrypt() got = %v, want %v", buf[:32], target[:32])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestMflac0Decoder_Validate(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
fileExt string
|
||||
wantErr bool
|
||||
}{
|
||||
{"mflac0_rc4", ".flac", false},
|
||||
{"mflac_map", ".flac", false},
|
||||
{"mgg_map", ".ogg", false},
|
||||
{"qmc0_static", ".mp3", false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
raw, _, err := loadTestDataQmcDecoder(tt.name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d := newDecoder(&decrypt.DecoderParams{
|
||||
Reader: bytes.NewReader(raw),
|
||||
Extension: tt.fileExt,
|
||||
})
|
||||
|
||||
if err := d.Validate(); err != nil {
|
||||
t.Errorf("read bytes from decoder error = %v", err)
|
||||
return
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user