Compare commits

..

No commits in common. "bc4109d0c0c84355b7dae33be22d5988c06bee5f" and "493ed8bdb5045e943e9b871378be71bff55d384d" have entirely different histories.

11 changed files with 32 additions and 207 deletions

1
Cargo.lock generated
View File

@ -434,7 +434,6 @@ dependencies = [
"anyhow", "anyhow",
"clap", "clap",
"umc_kuwo", "umc_kuwo",
"umc_ncm",
"umc_qmc", "umc_qmc",
"umc_utils", "umc_utils",
] ]

View File

@ -6,10 +6,9 @@
```text ```text
lib_um_crypto_rust lib_um_crypto_rust
├── um_cli 用于调试的 CLI 方案。 ├── um_crypto 子目录存放具体算法的代码
├── um_crypto/* 子目录存放具体算法的代码。 ├── um_wasm 将 um_crypto 包装为能从 JavaScript 层调用的代码
├── um_wasm 将 um_crypto 包装为能从 JavaScript 层调用的代码。 └── um_wasm_loader 打包 `um_wasm` 到 npm 包的代码
└── um_wasm_loader 打包 `um_wasm` 到 npm 包的代码。
``` ```
## 授权协议 ## 授权协议

View File

@ -8,5 +8,4 @@ anyhow = "1.0.86"
clap = { version = "4.5.17", features = ["derive"] } clap = { version = "4.5.17", features = ["derive"] }
umc_kuwo = { path = "../um_crypto/kuwo" } umc_kuwo = { path = "../um_crypto/kuwo" }
umc_qmc = { path = "../um_crypto/qmc" } umc_qmc = { path = "../um_crypto/qmc" }
umc_ncm = { path = "../um_crypto/ncm" }
umc_utils = { path = "../um_crypto/utils" } umc_utils = { path = "../um_crypto/utils" }

View File

@ -1,6 +1,5 @@
use clap::Subcommand; use clap::Subcommand;
pub mod ncm;
pub mod qmc1; pub mod qmc1;
pub mod qmc2; pub mod qmc2;
@ -10,6 +9,4 @@ pub enum Commands {
QMCv1(qmc1::ArgsQMCv1), QMCv1(qmc1::ArgsQMCv1),
#[command(name = "qmc2")] #[command(name = "qmc2")]
QMCv2(qmc2::ArgsQMCv2), QMCv2(qmc2::ArgsQMCv2),
#[command(name = "ncm")]
NCM(ncm::ArgsNCM),
} }

View File

@ -1,90 +0,0 @@
use crate::Cli;
use clap::Args;
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::PathBuf;
use umc_ncm::header::NCMFile;
/// Decrypt a NCM file (NetEase Cloud Music)
#[derive(Args)]
pub struct ArgsNCM {
/// Path to output file, e.g. /export/Music/song.flac
#[arg(short, long)]
output: Option<PathBuf>,
/// Path to input file, e.g. /export/Music/song.ncm
#[arg(name = "input")]
input: PathBuf,
/// Path to export cover image. Could be either JPG or PNG.
/// File will not be created if not found.
#[arg(short)]
cover: Option<PathBuf>,
/// Path to export metadata. JSON string.
#[arg(short)]
metadata: Option<PathBuf>,
}
impl ArgsNCM {
fn write_metadata(&self, cli: &Cli, ncm: &NCMFile) -> anyhow::Result<()> {
if let Some(metadata_path) = &self.metadata {
if !ncm.metadata.is_empty() {
let metadata = ncm.get_metadata()?;
File::create(metadata_path)?.write_all(&metadata)?;
if cli.verbose {
let metadata_path = metadata_path.display();
let len = metadata.len();
println!("metadata written to {metadata_path} ({len} bytes)");
}
} else {
println!("metadata is empty, skip.");
}
}
Ok(())
}
fn write_cover(&self, cli: &Cli, ncm: &NCMFile) -> anyhow::Result<()> {
if let Some(cover_path) = &self.cover {
if let Some(cover) = &ncm.image1 {
File::create(cover_path)?.write_all(&cover)?;
if cli.verbose {
let cover_path = cover_path.display();
let len = cover.len();
println!("cover written to {cover_path} ({len} bytes)");
}
} else {
println!("cover#1 is empty, skip.");
}
}
Ok(())
}
pub fn run(&self, cli: &Cli) -> anyhow::Result<i32> {
let mut file_input = File::open(&self.input)?;
let ncm = NCMFile::new_from_readable(&mut file_input)?;
self.write_metadata(cli, &ncm)?;
self.write_cover(cli, &ncm)?;
if let Some(output_path) = &self.output {
file_input.seek(SeekFrom::Start(ncm.audio_data_offset as u64))?;
let mut file_output = File::create(output_path)?;
let mut offset = 0usize;
let mut buffer = vec![0u8; cli.buffer_size].into_boxed_slice();
while let Ok(n) = file_input.read(&mut buffer) {
if n == 0 {
break;
}
ncm.decrypt(&mut buffer[..n], offset);
file_output.write_all(&buffer[..n])?;
offset += n;
}
}
Ok(0)
}
}

View File

@ -5,7 +5,7 @@ use std::fs::File;
use std::io::{Read, Write}; use std::io::{Read, Write};
use std::path::PathBuf; use std::path::PathBuf;
/// Decrypt a QMCv1 file (QQMusic) /// Decrypt a QMCv1 file
#[derive(Args)] #[derive(Args)]
pub struct ArgsQMCv1 { pub struct ArgsQMCv1 {
/// Path to output file, e.g. /export/Music/song.flac /// Path to output file, e.g. /export/Music/song.flac

View File

@ -8,7 +8,7 @@ use std::path::PathBuf;
use umc_qmc::{footer, QMCv2Cipher}; use umc_qmc::{footer, QMCv2Cipher};
use umc_utils::base64; use umc_utils::base64;
/// Decrypt a QMCv2 file (QQMusic) /// Decrypt a QMCv2 file
#[derive(Args)] #[derive(Args)]
pub struct ArgsQMCv2 { pub struct ArgsQMCv2 {
/// Path to output file, e.g. /export/Music/song.flac /// Path to output file, e.g. /export/Music/song.flac

View File

@ -29,7 +29,6 @@ fn run_command(cli: &Cli) -> Result<i32> {
match &cli.command { match &cli.command {
Some(Commands::QMCv1(cmd)) => cmd.run(&cli), Some(Commands::QMCv1(cmd)) => cmd.run(&cli),
Some(Commands::QMCv2(cmd)) => cmd.run(&cli), Some(Commands::QMCv2(cmd)) => cmd.run(&cli),
Some(Commands::NCM(cmd)) => cmd.run(&cli),
None => { None => {
// https://github.com/clap-rs/clap/issues/3857#issuecomment-1161796261 // https://github.com/clap-rs/clap/issues/3857#issuecomment-1161796261
todo!("implement a sensible default command, similar to um/cli"); todo!("implement a sensible default command, similar to um/cli");

View File

@ -1,26 +1,20 @@
use crate::{content_key, metadata, NetEaseCryptoError as Error, NetEaseCryptoError}; use crate::{content_key, NetEaseCryptoError as Error};
use byteorder::{ByteOrder, LE}; use byteorder::{ByteOrder, LE};
use std::cmp::max;
use std::io::Read;
const CRC32: crc::Crc<u32> = crc::Crc::<u32>::new(&crc::CRC_32_ISO_HDLC); const CRC32: crc::Crc<u32> = crc::Crc::<u32>::new(&crc::CRC_32_ISO_HDLC);
#[derive(Debug, PartialEq, Clone)] struct NCMFile {
pub struct NCMFile {
audio_rc4_key_stream: [u8; 256],
/// NCM File format version, 0x01
pub ncm_version: u8, pub ncm_version: u8,
/// CloudMusic client version (guess)
pub client_version: u8, pub client_version: u8,
/// Encrypted content key. /// Encrypted content key
pub content_key: Vec<u8>, pub content_key: Vec<u8>,
/// Encrypted metadata. /// Encrypted metadata.
pub metadata: Vec<u8>, pub metadata: Vec<u8>,
/// Cover image 1, usually jpg. /// Cover image 1
pub image1: Option<Vec<u8>>, pub image1: Option<Vec<u8>>,
/// Cover image 2, format unknown /// Cover image 2, format unknown
pub image2: Option<Vec<u8>>, pub image2: Option<Vec<u8>>,
audio_rc4_key_stream: [u8; 256],
pub audio_data_offset: usize, pub audio_data_offset: usize,
} }
@ -40,7 +34,6 @@ fn build_audio_rc4_key_stream(enciphered_content_key: &[u8]) -> Result<[u8; 256]
let mut key = [0u8; 256]; let mut key = [0u8; 256];
for (i, k) in key.iter_mut().enumerate() { for (i, k) in key.iter_mut().enumerate() {
let i = (i + 1) & 0xff;
let j = s[i].wrapping_add(i as u8); let j = s[i].wrapping_add(i as u8);
let idx = s[i].wrapping_add(s[j as usize]); let idx = s[i].wrapping_add(s[j as usize]);
*k = s[idx as usize]; *k = s[idx as usize];
@ -99,10 +92,10 @@ impl NCMFile {
let offset = offset + 1; let offset = offset + 1;
let cover_frame_len = LE::read_u32(&header[offset..offset + 4]) as usize; let cover_frame_len = LE::read_u32(&header[offset..offset + 4]) as usize;
let offset = offset + 4;
if header.len() < offset + cover_frame_len + 4 { if header.len() < offset + cover_frame_len + 4 {
Err(Error::HeaderTooSmall(offset + cover_frame_len + 4))?; Err(Error::HeaderTooSmall(offset + cover_frame_len + 4))?;
} }
let offset = offset + 4;
let image1_len = LE::read_u32(&header[offset..offset + 4]) as usize; let image1_len = LE::read_u32(&header[offset..offset + 4]) as usize;
if image1_len > cover_frame_len { if image1_len > cover_frame_len {
@ -112,7 +105,6 @@ impl NCMFile {
})?; })?;
} }
let offset = offset + 4; let offset = offset + 4;
let image2_len = cover_frame_len - image1_len; let image2_len = cover_frame_len - image1_len;
let image1 = match image1_len { let image1 = match image1_len {
0 => None, 0 => None,
@ -137,92 +129,35 @@ impl NCMFile {
audio_data_offset: offset, audio_data_offset: offset,
}) })
} }
pub fn new_from_readable<T>(file: &mut T) -> Result<Self, Error>
where
T: Read + ?Sized,
{
let mut total_bytes_read = 0;
let mut next_read_len = 4096;
let mut header = vec![];
let ncm = loop {
header.resize(total_bytes_read + next_read_len, 0);
let this_read = file
.read(&mut header[total_bytes_read..])
.map_err(NetEaseCryptoError::FileIOError)?;
if this_read == 0 {
Err(NetEaseCryptoError::FileIOErrorReadZero)?;
}
total_bytes_read += this_read;
match NCMFile::new(&header) {
Ok(ncm) => break ncm,
Err(NetEaseCryptoError::HeaderTooSmall(expected_len)) => {
next_read_len = max(expected_len - total_bytes_read, 4096);
}
Err(err) => Err(err)?,
};
};
Ok(ncm)
}
pub fn get_metadata(&self) -> Result<Vec<u8>, Error> {
metadata::decrypt(&self.metadata)
}
/// Decrypt audio data.
///
/// # Arguments
///
/// * `data`: The data to decrypt
/// * `offset`: Offset of the data in file, subtract `self.audio_data_offset`
pub fn decrypt<T>(&self, data: &mut T, offset: usize)
where
T: AsMut<[u8]> + ?Sized,
{
let key_stream = self.audio_rc4_key_stream.iter().cycle().skip(offset & 0xff);
for (datum, &key) in data.as_mut().iter_mut().zip(key_stream) {
*datum ^= key;
}
}
} }
#[test] #[test]
fn test_load_ncm() -> Result<(), Error> { fn test_load_ncm() -> Result<(), Error> {
let ncm_header = include_bytes!("__fixture__/ncm_test1.bin"); let ncm_header = include_bytes!("__fixture__/ncm_test1.bin");
let ncm = NCMFile::new(ncm_header)?; let ncm = NCMFile::new(ncm_header)?;
let key_stream = [ let sbox = [
0x67, 0x20, 0xF0, 0x5C, 0xAC, 0xAF, 0x1B, 0x74, 0x0D, 0x26, 0x40, 0xBE, 0x85, 0x61, 0x45, 0x08, 0x67, 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0x66, 0xBB, 0x4F, 0x7E, 0xBC, 0x99, 0x76, 0x1A, 0xD2,
0xBE, 0xD9, 0x79, 0xA0, 0x33, 0xD5, 0x96, 0x6C, 0xD9, 0xEF, 0x42, 0x7E, 0x11, 0x45, 0x1F, 0xEF, 0xBE, 0xD9, 0x79, 0xA0, 0x33, 0xD5, 0x96, 0x6C, 0xD9, 0xEF, 0x42, 0x7E, 0x11, 0x45,
0x99, 0x96, 0x1A, 0x90, 0x0C, 0x75, 0xBC, 0x01, 0xE2, 0xC8, 0xEF, 0x16, 0x98, 0x9A, 0x09, 0x1F, 0x99, 0x96, 0x1A, 0x90, 0x0C, 0x75, 0xBC, 0x01, 0xE2, 0xC8, 0xEF, 0x16, 0x98, 0x9A,
0xEB, 0xD8, 0xA1, 0xEA, 0x62, 0xE7, 0x92, 0x20, 0x8F, 0x6F, 0x72, 0xDE, 0x14, 0xFE, 0xBF, 0x09, 0xEB, 0xD8, 0xA1, 0xEA, 0x62, 0xE7, 0x92, 0x20, 0x8F, 0x6F, 0x72, 0xDE, 0x14, 0xFE,
0xCD, 0xBA, 0x97, 0xDE, 0xA3, 0x3B, 0x67, 0xD4, 0x0B, 0xF4, 0xD3, 0x97, 0x25, 0xBA, 0xCA, 0xBF, 0xCD, 0xBA, 0x97, 0xDE, 0xA3, 0x3B, 0x67, 0xD4, 0x0B, 0xF4, 0xD3, 0x97, 0x25, 0xBA,
0x08, 0xCA,
]; ];
assert_eq!(ncm.audio_rc4_key_stream, key_stream); assert_eq!(ncm.audio_rc4_key_stream, sbox);
assert_eq!(ncm.image1, Some(b"img#1".to_vec())); assert_eq!(ncm.image1, Some(b"img#1".to_vec()));
assert_eq!(ncm.image2, Some(b"IMAGE#2".to_vec())); assert_eq!(ncm.image2, Some(b"IMAGE#2".to_vec()));
let mut audio_data = ncm_header[ncm.audio_data_offset..].to_vec();
ncm.decrypt(&mut audio_data, 0);
let actual = vec![
0x49, 0x44, 0x33, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x73, 0x54, 0x50, 0x45, 0x31, 0x00,
];
assert_eq!(audio_data, actual);
Ok(()) Ok(())
} }

View File

@ -11,11 +11,6 @@ pub enum NetEaseCryptoError {
#[error("Header need at least {0} more bytes")] #[error("Header need at least {0} more bytes")]
HeaderTooSmall(usize), HeaderTooSmall(usize),
#[error("File I/O Error: {0}")]
FileIOError(std::io::Error),
#[error("File I/O Error: Read 0 bytes")]
FileIOErrorReadZero,
#[error("Not a NCM file")] #[error("Not a NCM file")]
NotNCMFile, NotNCMFile,
#[error("Invalid NCM checksum. Expected {expected:08x}, actual: {expected:08x}")] #[error("Invalid NCM checksum. Expected {expected:08x}, actual: {expected:08x}")]
@ -39,6 +34,4 @@ pub enum NetEaseCryptoError {
MetadataDecryptError(UnpadError), MetadataDecryptError(UnpadError),
#[error("Metadata: Decode metadata failed: {0}")] #[error("Metadata: Decode metadata failed: {0}")]
MetadataDecodeError(base64::DecodeError), MetadataDecodeError(base64::DecodeError),
#[error("Metadata: Invalid prefix on final json: {0}")]
MetadataInvalidJsonPrefix(String),
} }

View File

@ -35,12 +35,6 @@ where
let metadata = aes let metadata = aes
.decrypt_padded::<Pkcs7>(&mut data[..]) .decrypt_padded::<Pkcs7>(&mut data[..])
.map_err(NetEaseCryptoError::MetadataDecryptError)?; .map_err(NetEaseCryptoError::MetadataDecryptError)?;
let metadata = match metadata.strip_prefix(b"music:") {
None => Err(NetEaseCryptoError::MetadataInvalidJsonPrefix(
String::from_utf8_lossy(metadata).to_string(),
))?,
Some(stripped) => stripped,
};
Ok(Vec::from(metadata)) Ok(Vec::from(metadata))
} }
@ -106,6 +100,6 @@ fn test_decrypt_metadata() -> Result<(), NetEaseCryptoError> {
0x25, 0x1B, 0x37, 0x48, 0x57, 0x53, 0x2A, 0x22, 0x3A, 0x00, 0x34, 0x53, 0x24, 0x12, 0x25, 0x1B, 0x37, 0x48, 0x57, 0x53, 0x2A, 0x22, 0x3A, 0x00, 0x34, 0x53, 0x24, 0x12,
]; ];
let key = decrypt(enciphered_metadata)?; let key = decrypt(enciphered_metadata)?;
assert_eq!(key[0], b'{'); assert_eq!(&key[..6], b"music:");
Ok(()) Ok(())
} }