unityrs_core/codec/
unitycn.rs1use aes::Aes128;
14use aes::cipher::{BlockEncrypt, KeyInit};
15
16use crate::codec::BlockDecryptor;
17use crate::stream::Reader;
18use crate::{Error, Unsupported};
19
20#[derive(Clone)]
22pub struct UnityCnDecryptor {
23 index: [u8; 16],
24 substitute: [u8; 16],
25}
26
27impl std::fmt::Debug for UnityCnDecryptor {
28 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29 f.debug_struct("UnityCnDecryptor").finish_non_exhaustive()
30 }
31}
32
33const _: () = crate::send_sync::<UnityCnDecryptor>();
34
35impl UnityCnDecryptor {
36 #[must_use]
38 pub fn from_tables(index: [u8; 16], substitute: [u8; 16]) -> Self {
39 Self { index, substitute }
40 }
41 pub fn read(r: &mut Reader<'_>, key: Option<&[u8; 16]>) -> Result<Self, Error> {
44 Self::read_with_key(r, || Ok(key.copied()))
45 }
46
47 pub(crate) fn read_with_key(
49 r: &mut Reader<'_>,
50 key: impl FnOnce() -> Result<Option<[u8; 16]>, Error>,
51 ) -> Result<Self, Error> {
52 r.read_u32()?;
53 let (data, vector) = read_vector(r)?;
54 let (signature, signature_vector) = read_vector(r)?;
55 let key = key()?.ok_or(Error::UnityCnKeyMissing)?;
56 let (decoded, len) = decrypt_key(signature_vector, signature, &key)?;
57 if len != 16 || &decoded != b"#$unity3dchina!@" {
58 return Err(Error::UnityCnSignature);
59 }
60 let (decoded, len) = decrypt_key(vector, data, &key)?;
61 if len != 16 {
62 return Err(Error::UnityCnSignature);
63 }
64 let mut nibbles = [0; 32];
65 for (pair, byte) in nibbles.as_chunks_mut::<2>().0.iter_mut().zip(decoded) {
66 pair.copy_from_slice(&[byte >> 4, byte & 15]);
67 }
68 let mut index = [0; 16];
69 let mut substitute = [0; 16];
70 for (to, from) in index.iter_mut().zip(nibbles.iter()) {
71 *to = *from;
72 }
73 for (n, to) in substitute.iter_mut().enumerate() {
74 *to = nibbles.get(16 + (n % 4) * 4 + n / 4).copied().unwrap_or(0);
75 }
76 Ok(Self { index, substitute })
77 }
78
79 fn byte(&self, byte: u8, index: usize) -> u8 {
80 let get = |table: &[u8; 16], i| table.get(i).copied().unwrap_or(0);
81 let b = get(&self.substitute, ((index >> 2) & 3) + 4)
82 .wrapping_add(get(&self.substitute, index & 3))
83 .wrapping_add(get(&self.substitute, ((index >> 4) & 3) + 8))
84 .wrapping_add(get(&self.substitute, ((index >> 6) & 3) + 12));
85 (get(&self.index, usize::from(byte & 15)).wrapping_sub(b) & 15)
86 | (get(&self.index, usize::from(byte >> 4)).wrapping_sub(b) << 4)
87 }
88
89 fn next(&self, bytes: &mut [u8], at: &mut usize, index: &mut usize) -> Result<u8, Error> {
90 let value = if let Some(byte) = bytes.get_mut(*at) {
91 *byte = self.byte(*byte, *index);
92 *byte
93 } else if *at == bytes.len() {
94 self.byte(0, *index)
95 } else {
96 return Err(Error::Unsupported(Unsupported::UnityCnWalk));
97 };
98 *at = at.saturating_add(1);
99 *index = index.wrapping_add(1);
100 Ok(value)
101 }
102}
103
104pub fn decrypt_key_bytes(
107 vector: &[u8],
108 data: &[u8],
109 key: &[u8],
110 meter: &std::sync::Arc<crate::limits::Meter>,
111) -> Result<crate::limits::MeteredVec<u8>, Error> {
112 use aes::{Aes192, Aes256};
113 if !vector.len().is_multiple_of(16) {
114 return Err(Error::UnityCnVectorLength {
115 length: vector.len(),
116 });
117 }
118 let mut out = crate::limits::MeteredVec::new(meter);
119 macro_rules! apply {
120 ($cipher:ty) => {{
121 let cipher = <$cipher>::new_from_slice(key).map_err(|_| Error::UnityCnSignature)?;
122 for (block, data) in vector.chunks_exact(16).zip(data.chunks(16)) {
123 meter.count_decode(16)?;
124 let mut bytes = aes::cipher::Block::<$cipher>::default();
125 bytes.copy_from_slice(block);
126 cipher.encrypt_block(&mut bytes);
127 for (mask, value) in bytes.iter().zip(data) {
128 out.push(mask ^ value)?;
129 }
130 }
131 }};
132 }
133 match key.len() {
134 16 => apply!(Aes128),
135 24 => apply!(Aes192),
136 32 => apply!(Aes256),
137 _ => return Err(Error::UnityCnSignature),
138 }
139 Ok(out)
140}
141
142impl BlockDecryptor for UnityCnDecryptor {
143 fn decrypt(&self, block: &mut [u8], mut index: usize) -> Result<(), Error> {
146 let mut at = 0;
147 while at < block.len() {
148 let mut sequence_index = index;
149 let token = self.next(block, &mut at, &mut sequence_index)?;
150 let mut literals = usize::from(token >> 4);
151 if literals == 15 {
152 loop {
153 let b = self.next(block, &mut at, &mut sequence_index)?;
154 literals = literals.saturating_add(usize::from(b));
155 if b != 255 {
156 break;
157 }
158 }
159 }
160 at = at.saturating_add(literals);
162 if at < block.len() {
163 self.next(block, &mut at, &mut sequence_index)?;
164 self.next(block, &mut at, &mut sequence_index)?;
165 if token & 15 == 15 {
166 loop {
167 if self.next(block, &mut at, &mut sequence_index)? != 255 {
168 break;
169 }
170 }
171 }
172 }
173 index = index.wrapping_add(1);
174 }
175 Ok(())
176 }
177}
178
179fn read_vector<'a>(r: &mut Reader<'a>) -> Result<(&'a [u8], &'a [u8]), Error> {
181 let data = r.read_bytes_short(16);
182 let key = r.read_bytes_short(16);
183 r.set_position(r.position() + 1)?;
184 Ok((data, key))
185}
186
187fn decrypt_key(vector: &[u8], data: &[u8], key: &[u8; 16]) -> Result<([u8; 16], usize), Error> {
189 if vector.is_empty() {
192 return Ok(([0; 16], 0));
193 }
194 let vector = <[u8; 16]>::try_from(vector).map_err(|_| Error::UnityCnVectorLength {
195 length: vector.len(),
196 })?;
197 let cipher = Aes128::new(&(*key).into());
198 let mut block = vector.into();
199 cipher.encrypt_block(&mut block);
200 let mut out = [0; 16];
201 for ((to, from), mask) in out.iter_mut().zip(data).zip(block) {
202 *to = from ^ mask;
203 }
204 Ok((out, data.len().min(16)))
205}
206
207#[cfg(test)]
208mod tests;