Restructure into a workspace

This commit is contained in:
Alex Page 2023-06-24 17:11:37 -04:00
parent 589f0bb52b
commit fe08910831
16 changed files with 534 additions and 39 deletions

310
umskt/src/bink1998.rs Normal file
View file

@ -0,0 +1,310 @@
use std::fmt::{Display, Formatter};
use anyhow::{bail, Result};
use bitreader::BitReader;
use openssl::{
bn::{BigNum, BigNumContext, MsbOption},
ec::{EcGroup, EcPoint},
sha::sha1,
};
use crate::{
crypto::{EllipticCurve, PrivateKey},
key::{base24_decode, base24_encode, strip_key},
math::bitmask,
};
const FIELD_BITS: i32 = 384;
const FIELD_BYTES: usize = 48;
const SHA_MSG_LENGTH: usize = 4 + 2 * FIELD_BYTES;
const HASH_LENGTH_BITS: u8 = 28;
const SERIAL_LENGTH_BITS: u8 = 30;
const UPGRADE_LENGTH_BITS: u8 = 1;
const EVERYTHING_ELSE: u8 = HASH_LENGTH_BITS + SERIAL_LENGTH_BITS + UPGRADE_LENGTH_BITS;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ProductKey {
upgrade: bool,
channel_id: u32,
sequence: u32,
hash: u32,
signature: u64,
}
impl ProductKey {
pub fn new(
curve: &EllipticCurve,
private_key: &PrivateKey,
channel_id: u32,
sequence: Option<u32>,
upgrade: Option<bool>,
) -> Result<Self> {
// Generate random sequence if none supplied
let sequence = match sequence {
Some(serial) => serial,
None => {
let mut bn_rand = BigNum::new()?;
bn_rand.rand(19, MsbOption::MAYBE_ZERO, false)?;
let o_raw = u32::from_be_bytes(bn_rand.to_vec_padded(4)?.try_into().unwrap());
o_raw % 999999
}
};
// Default to upgrade=false
let upgrade = upgrade.unwrap_or(false);
// Generate a new random key
let product_key = Self::generate(
&curve.curve,
&curve.gen_point,
&private_key.gen_order,
&private_key.private_key,
channel_id,
sequence,
upgrade,
)?;
// Make sure the key is valid
product_key.verify(&curve.curve, &curve.gen_point, &curve.pub_point)?;
// Ship it
Ok(product_key)
}
pub fn from_key(curve: &EllipticCurve, key: &str) -> Result<Self> {
let key = strip_key(key)?;
let Ok(packed_key) = base24_decode(&key) else {
bail!("Product key is in an incorrect format!")
};
let product_key = Self::from_packed(&packed_key)?;
product_key.verify(&curve.curve, &curve.gen_point, &curve.pub_point)?;
Ok(product_key)
}
fn generate(
e_curve: &EcGroup,
base_point: &EcPoint,
gen_order: &BigNum,
private_key: &BigNum,
channel_id: u32,
sequence: u32,
upgrade: bool,
) -> Result<Self> {
let mut num_context = BigNumContext::new().unwrap();
let mut c = BigNum::new()?;
let mut s = BigNum::new()?;
let mut x = BigNum::new()?;
let mut y = BigNum::new()?;
let mut ek: BigNum;
let serial = channel_id * 1_000_000 + sequence;
let data = serial << 1 | upgrade as u32;
let product_key = loop {
let mut r = EcPoint::new(e_curve)?;
// Generate a random number c consisting of 384 bits without any constraints.
c.rand(FIELD_BITS, MsbOption::MAYBE_ZERO, false)?;
// Pick a random derivative of the base point on the elliptic curve.
// R = cG;
r.mul(e_curve, base_point, &c, &num_context)?;
// Acquire its coordinates.
// x = R.x; y = R.y;
r.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?;
let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH];
let mut x_bin = x.to_vec_padded(FIELD_BYTES as i32)?;
x_bin.reverse();
let mut y_bin = y.to_vec_padded(FIELD_BYTES as i32)?;
y_bin.reverse();
msg_buffer[0..4].copy_from_slice(&data.to_le_bytes());
msg_buffer[4..4 + FIELD_BYTES].copy_from_slice(&x_bin);
msg_buffer[4 + FIELD_BYTES..4 + FIELD_BYTES * 2].copy_from_slice(&y_bin);
let msg_digest = sha1(&msg_buffer);
let hash: u32 =
u32::from_le_bytes(msg_digest[0..4].try_into().unwrap()) >> 4 & bitmask(28) as u32;
ek = (*private_key).to_owned()?;
ek.mul_word(hash)?;
s.mod_add(&ek, &c, gen_order, &mut num_context)?;
let signature = u64::from_be_bytes(s.to_vec_padded(8)?.try_into().unwrap());
if signature <= bitmask(55) {
break Self {
upgrade,
channel_id,
sequence,
hash,
signature,
};
}
};
Ok(product_key)
}
fn verify(
&self,
e_curve: &EcGroup,
base_point: &EcPoint,
public_key: &EcPoint,
) -> Result<bool> {
let mut ctx = BigNumContext::new()?;
let e = BigNum::from_u32(self.hash)?;
let s = BigNum::from_slice(&self.signature.to_be_bytes())?;
let mut x = BigNum::new()?;
let mut y = BigNum::new()?;
let mut t = EcPoint::new(e_curve)?;
let mut p = EcPoint::new(e_curve)?;
t.mul(e_curve, base_point, &s, &ctx)?;
p.mul(e_curve, public_key, &e, &ctx)?;
{
let p_copy = p.to_owned(e_curve)?;
p.add(e_curve, &t, &p_copy, &mut ctx)?;
}
p.affine_coordinates(e_curve, &mut x, &mut y, &mut ctx)?;
let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH];
let mut x_bin = x.to_vec_padded(FIELD_BYTES as i32)?;
x_bin.reverse();
let mut y_bin = y.to_vec_padded(FIELD_BYTES as i32)?;
y_bin.reverse();
let serial = self.channel_id * 1_000_000 + self.sequence;
let data = serial << 1 | self.upgrade as u32;
msg_buffer[0..4].copy_from_slice(&data.to_le_bytes());
msg_buffer[4..4 + FIELD_BYTES].copy_from_slice(&x_bin);
msg_buffer[4 + FIELD_BYTES..4 + FIELD_BYTES * 2].copy_from_slice(&y_bin);
let msg_digest = sha1(&msg_buffer);
let hash: u32 =
u32::from_le_bytes(msg_digest[0..4].try_into().unwrap()) >> 4 & bitmask(28) as u32;
Ok(hash == self.hash)
}
fn from_packed(packed_key: &[u8]) -> Result<Self> {
let mut reader = BitReader::new(packed_key);
// The signature length isn't known, but everything else is, so we can calculate it
let signature_length_bits = (packed_key.len() * 8) as u8 - EVERYTHING_ELSE;
let signature = reader.read_u64(signature_length_bits)?;
let hash = reader.read_u32(HASH_LENGTH_BITS)?;
let serial = reader.read_u32(SERIAL_LENGTH_BITS)?;
let upgrade = reader.read_bool()?;
let sequence = serial % 1_000_000;
let channel_id = serial / 1_000_000;
Ok(Self {
upgrade,
channel_id,
sequence,
hash,
signature,
})
}
fn pack(&self) -> Vec<u8> {
let mut packed_key: u128 = 0;
let serial = self.channel_id * 1_000_000 + self.sequence;
packed_key |= (self.signature as u128) << EVERYTHING_ELSE;
packed_key |= (self.hash as u128) << (SERIAL_LENGTH_BITS + UPGRADE_LENGTH_BITS);
packed_key |= (serial as u128) << UPGRADE_LENGTH_BITS;
packed_key |= self.upgrade as u128;
packed_key
.to_be_bytes()
.into_iter()
.skip_while(|&x| x == 0)
.collect()
}
}
impl Display for ProductKey {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let pk = base24_encode(&self.pack()).unwrap();
let key = pk
.chars()
.enumerate()
.fold(String::new(), |mut acc: String, (i, c)| {
if i > 0 && i % 5 == 0 {
acc.push('-');
}
acc.push(c);
acc
});
write!(f, "{}", key)
}
}
#[cfg(test)]
mod tests {
use std::{fs::File, io::BufReader};
use serde_json::from_reader;
use crate::crypto::EllipticCurve;
#[test]
fn verify_test() {
// Example product key and its BINK ID
let product_key = "D9924-R6BG2-39J83-RYKHF-W47TT";
let bink_id = "2E";
// Load keys.json
let path = "keys.json";
let file = File::open(path).unwrap();
let reader = BufReader::new(file);
let keys: serde_json::Value = from_reader(reader).unwrap();
let bink = &keys["BINK"][&bink_id];
let p = bink["p"].as_str().unwrap();
let a = bink["a"].as_str().unwrap();
let b = bink["b"].as_str().unwrap();
let gx = bink["g"]["x"].as_str().unwrap();
let gy = bink["g"]["y"].as_str().unwrap();
let kx = bink["pub"]["x"].as_str().unwrap();
let ky = bink["pub"]["y"].as_str().unwrap();
let curve = EllipticCurve::new(p, a, b, gx, gy, kx, ky).unwrap();
assert!(super::ProductKey::from_key(&curve, product_key).is_ok());
assert!(super::ProductKey::from_key(&curve, "11111-R6BG2-39J83-RYKHF-W47TT").is_err());
}
#[test]
fn pack_test() {
let key = super::ProductKey {
upgrade: false,
channel_id: 640,
sequence: 10550,
hash: 39185432,
signature: 6939952665262054,
};
assert_eq!(key.to_string(), "D9924-R6BG2-39J83-RYKHF-W47TT");
}
}

367
umskt/src/bink2002.rs Normal file
View file

@ -0,0 +1,367 @@
use std::fmt::{Display, Formatter};
use anyhow::{bail, Result};
use bitreader::BitReader;
use openssl::{
bn::{BigNum, BigNumContext, MsbOption},
ec::{EcGroup, EcPoint},
rand::rand_bytes,
sha::sha1,
};
use crate::{
crypto::{EllipticCurve, PrivateKey},
key::{base24_decode, base24_encode, strip_key},
math::{bitmask, by_dword, next_sn_bits},
};
const FIELD_BITS: i32 = 512;
const FIELD_BYTES: usize = 64;
const SHA_MSG_LENGTH: usize = 3 + 2 * FIELD_BYTES;
const SIGNATURE_LENGTH_BITS: u8 = 62;
const HASH_LENGTH_BITS: u8 = 31;
const CHANNEL_ID_LENGTH_BITS: u8 = 10;
const UPGRADE_LENGTH_BITS: u8 = 1;
const EVERYTHING_ELSE: u8 =
SIGNATURE_LENGTH_BITS + HASH_LENGTH_BITS + CHANNEL_ID_LENGTH_BITS + UPGRADE_LENGTH_BITS;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ProductKey {
upgrade: bool,
channel_id: u32,
hash: u32,
signature: u64,
auth_info: u32,
}
impl ProductKey {
pub fn new(
curve: &EllipticCurve,
private_key: &PrivateKey,
channel_id: u32,
auth_info: Option<u32>,
upgrade: Option<bool>,
) -> Result<Self> {
// Generate random auth info if none supplied
let auth_info = match auth_info {
Some(auth_info) => auth_info,
None => {
let mut auth_info_bytes = [0_u8; 4];
rand_bytes(&mut auth_info_bytes)?;
u32::from_ne_bytes(auth_info_bytes) & ((1 << 10) - 1)
}
};
// Default to upgrade=false
let upgrade = upgrade.unwrap_or(false);
// Generate a new random key
let product_key = Self::generate(
&curve.curve,
&curve.gen_point,
&private_key.gen_order,
&private_key.private_key,
channel_id,
auth_info,
upgrade,
)?;
// Make sure the key is valid
product_key.verify(&curve.curve, &curve.gen_point, &curve.pub_point)?;
// Ship it
Ok(product_key)
}
pub fn from_key(curve: &EllipticCurve, key: &str) -> Result<Self> {
let key = strip_key(key)?;
let Ok(packed_key) = base24_decode(&key) else {
bail!("Product key is in an incorrect format!")
};
let product_key = Self::from_packed(&packed_key)?;
let verified = product_key.verify(&curve.curve, &curve.gen_point, &curve.pub_point)?;
if !verified {
bail!("Product key is invalid! Wrong BINK ID?");
}
Ok(product_key)
}
fn generate(
e_curve: &EcGroup,
base_point: &EcPoint,
gen_order: &BigNum,
private_key: &BigNum,
channel_id: u32,
auth_info: u32,
upgrade: bool,
) -> Result<Self> {
let mut num_context = BigNumContext::new().unwrap();
let mut c = BigNum::new()?;
let mut x = BigNum::new()?;
let mut y = BigNum::new()?;
let data = channel_id << 1 | upgrade as u32;
let mut no_square = false;
let key = loop {
let mut r = EcPoint::new(e_curve)?;
c.rand(FIELD_BITS, MsbOption::MAYBE_ZERO, false)?;
r.mul(e_curve, base_point, &c, &num_context)?;
r.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?;
let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH];
let mut x_bin = x.to_vec_padded(FIELD_BYTES as i32)?;
x_bin.reverse();
let mut y_bin = y.to_vec_padded(FIELD_BYTES as i32)?;
y_bin.reverse();
msg_buffer[0x00] = 0x79;
msg_buffer[0x01] = (data & 0x00FF) as u8;
msg_buffer[0x02] = ((data & 0xFF00) >> 8) as u8;
msg_buffer[3..3 + FIELD_BYTES].copy_from_slice(&x_bin);
msg_buffer[3 + FIELD_BYTES..3 + FIELD_BYTES * 2].copy_from_slice(&y_bin);
let msg_digest = sha1(&msg_buffer);
let hash: u32 = by_dword(&msg_digest[0..4]) & bitmask(31) as u32;
msg_buffer[0x00] = 0x5D;
msg_buffer[0x01] = (data & 0x00FF) as u8;
msg_buffer[0x02] = ((data & 0xFF00) >> 8) as u8;
msg_buffer[0x03] = (hash & 0x000000FF) as u8;
msg_buffer[0x04] = ((hash & 0x0000FF00) >> 8) as u8;
msg_buffer[0x05] = ((hash & 0x00FF0000) >> 16) as u8;
msg_buffer[0x06] = ((hash & 0xFF000000) >> 24) as u8;
msg_buffer[0x07] = (auth_info & 0x00FF) as u8;
msg_buffer[0x08] = ((auth_info & 0xFF00) >> 8) as u8;
msg_buffer[0x09] = 0x00;
msg_buffer[0x0A] = 0x00;
let msg_digest = sha1(&msg_buffer[..=0x0A]);
let i_signature = next_sn_bits(by_dword(&msg_digest[4..8]) as u64, 30, 2) << 32
| by_dword(&msg_digest[0..4]) as u64;
let mut e = BigNum::from_slice(&i_signature.to_be_bytes())?;
let e_2 = e.to_owned()?;
e.mod_mul(&e_2, private_key, gen_order, &mut num_context)?;
let mut s = e.to_owned()?;
let s_2 = s.to_owned()?;
s.mod_sqr(&s_2, gen_order, &mut num_context)?;
let c_2 = c.to_owned()?;
c.lshift(&c_2, 2)?;
s = &s + &c;
let s_2 = s.to_owned()?;
if s.mod_sqrt(&s_2, gen_order, &mut num_context).is_err() {
no_square = true;
};
let s_2 = s.to_owned()?;
s.mod_sub(&s_2, &e, gen_order, &mut num_context)?;
if s.is_bit_set(0) {
s = &s + gen_order;
}
let s_2 = s.to_owned()?;
s.rshift1(&s_2)?;
let signature = u64::from_be_bytes(s.to_vec_padded(8)?.try_into().unwrap());
let product_key = Self {
upgrade,
channel_id,
hash,
signature,
auth_info,
};
if signature <= bitmask(62) && !no_square {
break product_key;
}
no_square = false;
};
Ok(key)
}
fn verify(
&self,
e_curve: &EcGroup,
base_point: &EcPoint,
public_key: &EcPoint,
) -> Result<bool> {
let mut num_context = BigNumContext::new()?;
let data = self.channel_id << 1 | self.upgrade as u32;
let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH];
msg_buffer[0x00] = 0x5D;
msg_buffer[0x01] = (data & 0x00FF) as u8;
msg_buffer[0x02] = ((data & 0xFF00) >> 8) as u8;
msg_buffer[0x03] = (self.hash & 0x000000FF) as u8;
msg_buffer[0x04] = ((self.hash & 0x0000FF00) >> 8) as u8;
msg_buffer[0x05] = ((self.hash & 0x00FF0000) >> 16) as u8;
msg_buffer[0x06] = ((self.hash & 0xFF000000) >> 24) as u8;
msg_buffer[0x07] = (self.auth_info & 0x00FF) as u8;
msg_buffer[0x08] = ((self.auth_info & 0xFF00) >> 8) as u8;
msg_buffer[0x09] = 0x00;
msg_buffer[0x0A] = 0x00;
let msg_digest = sha1(&msg_buffer[..=0x0A]);
let i_signature = next_sn_bits(by_dword(&msg_digest[4..8]) as u64, 30, 2) << 32
| by_dword(&msg_digest[0..4]) as u64;
let e = BigNum::from_slice(&i_signature.to_be_bytes())?;
let s = BigNum::from_slice(&self.signature.to_be_bytes())?;
let mut x = BigNum::new()?;
let mut y = BigNum::new()?;
let mut p = EcPoint::new(e_curve)?;
let mut t = EcPoint::new(e_curve)?;
t.mul(e_curve, base_point, &s, &num_context)?;
p.mul(e_curve, public_key, &e, &num_context)?;
{
let p_2 = p.to_owned(e_curve)?;
p.add(e_curve, &t, &p_2, &mut num_context)?;
}
{
let p_2 = p.to_owned(e_curve)?;
p.mul(e_curve, &p_2, &s, &num_context)?;
}
p.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?;
let mut x_bin = x.to_vec_padded(FIELD_BYTES as i32)?;
x_bin.reverse();
let mut y_bin = y.to_vec_padded(FIELD_BYTES as i32)?;
y_bin.reverse();
msg_buffer[0x00] = 0x79;
msg_buffer[0x01] = (data & 0x00FF) as u8;
msg_buffer[0x02] = ((data & 0xFF00) >> 8) as u8;
msg_buffer[3..3 + FIELD_BYTES].copy_from_slice(&x_bin);
msg_buffer[3 + FIELD_BYTES..3 + FIELD_BYTES * 2].copy_from_slice(&y_bin);
let msg_digest = sha1(&msg_buffer);
let hash: u32 = by_dword(&msg_digest[0..4]) & bitmask(31) as u32;
Ok(hash == self.hash)
}
fn from_packed(packed_key: &[u8]) -> Result<Self> {
let mut reader = BitReader::new(packed_key);
// The auth info length isn't known, but everything else is, so we can calculate it
let auth_info_length_bits = (packed_key.len() * 8) as u8 - EVERYTHING_ELSE;
let auth_info = reader.read_u32(auth_info_length_bits)?;
let signature = reader.read_u64(SIGNATURE_LENGTH_BITS)?;
let hash = reader.read_u32(HASH_LENGTH_BITS)?;
let channel_id = reader.read_u32(CHANNEL_ID_LENGTH_BITS)?;
let upgrade = reader.read_bool()?;
Ok(Self {
upgrade,
channel_id,
hash,
signature,
auth_info,
})
}
fn pack(&self) -> Vec<u8> {
let mut packed_key: u128 = 0;
packed_key |= (self.auth_info as u128)
<< (SIGNATURE_LENGTH_BITS
+ HASH_LENGTH_BITS
+ CHANNEL_ID_LENGTH_BITS
+ UPGRADE_LENGTH_BITS);
packed_key |= (self.signature as u128)
<< (HASH_LENGTH_BITS + CHANNEL_ID_LENGTH_BITS + UPGRADE_LENGTH_BITS);
packed_key |= (self.hash as u128) << (CHANNEL_ID_LENGTH_BITS + UPGRADE_LENGTH_BITS);
packed_key |= (self.channel_id as u128) << UPGRADE_LENGTH_BITS;
packed_key |= self.upgrade as u128;
packed_key
.to_be_bytes()
.into_iter()
.skip_while(|&x| x == 0)
.collect()
}
}
impl Display for ProductKey {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let pk = base24_encode(&self.pack()).unwrap();
let key = pk
.chars()
.enumerate()
.fold(String::new(), |mut acc: String, (i, c)| {
if i > 0 && i % 5 == 0 {
acc.push('-');
}
acc.push(c);
acc
});
write!(f, "{}", key)
}
}
#[cfg(test)]
mod tests {
use serde_json::from_reader;
use std::{fs::File, io::BufReader};
use crate::crypto::EllipticCurve;
#[test]
fn verify_test() {
// Example product key and its BINK ID
let product_key = "R882X-YRGC8-4KYTG-C3FCC-JCFDY";
let bink_id = "54";
// Load keys.json
let path = "keys.json";
let file = File::open(path).unwrap();
let reader = BufReader::new(file);
let keys: serde_json::Value = from_reader(reader).unwrap();
let bink = &keys["BINK"][&bink_id];
let p = bink["p"].as_str().unwrap();
let a = bink["a"].as_str().unwrap();
let b = bink["b"].as_str().unwrap();
let gx = bink["g"]["x"].as_str().unwrap();
let gy = bink["g"]["y"].as_str().unwrap();
let kx = bink["pub"]["x"].as_str().unwrap();
let ky = bink["pub"]["y"].as_str().unwrap();
let curve = EllipticCurve::new(p, a, b, gx, gy, kx, ky).unwrap();
assert!(super::ProductKey::from_key(&curve, product_key).is_ok());
assert!(super::ProductKey::from_key(&curve, "11111-YRGC8-4KYTG-C3FCC-JCFDY").is_err());
}
}

File diff suppressed because it is too large Load diff

78
umskt/src/confid/mod.rs Normal file
View file

@ -0,0 +1,78 @@
use std::ffi::{CStr, CString};
use thiserror::Error;
mod black_box;
#[derive(Error, Debug, PartialEq, Eq)]
pub enum ConfirmationIdError {
#[error("Installation ID is too short.")]
TooShort,
#[error("Installation ID is too long.")]
TooLarge,
#[error("Invalid character in installation ID.")]
InvalidCharacter,
#[error("Installation ID checksum failed. Please check that it is typed correctly.")]
InvalidCheckDigit,
#[error("Unknown installation ID version.")]
UnknownVersion,
#[error("Unable to generate valid confirmation ID.")]
Unlucky,
}
pub fn generate(installation_id: &str) -> Result<String, ConfirmationIdError> {
if installation_id.len() < 54 {
return Err(ConfirmationIdError::TooShort);
}
if installation_id.len() > 54 {
return Err(ConfirmationIdError::TooLarge);
}
let inst_id = CString::new(installation_id).unwrap();
let conf_id = [0u8; 49];
let result = unsafe { black_box::generate(inst_id.as_ptr(), conf_id.as_ptr() as *mut i8) };
match result {
0 => {}
1 => return Err(ConfirmationIdError::TooShort),
2 => return Err(ConfirmationIdError::TooLarge),
3 => return Err(ConfirmationIdError::InvalidCharacter),
4 => return Err(ConfirmationIdError::InvalidCheckDigit),
5 => return Err(ConfirmationIdError::UnknownVersion),
6 => return Err(ConfirmationIdError::Unlucky),
_ => panic!("Unknown error code: {}", result),
}
unsafe {
Ok(CStr::from_ptr(conf_id.as_ptr() as *const i8)
.to_str()
.unwrap()
.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_generate() {
assert_eq!(
generate("334481558826870862843844566221823392794862457401103810").unwrap(),
"110281-200130-887120-647974-697175-027544-252733"
);
assert!(
generate("33448155882687086284384456622182339279486245740110381")
.is_err_and(|err| err == ConfirmationIdError::TooShort),
);
assert!(
generate("3344815588268708628438445662218233927948624574011038100")
.is_err_and(|err| err == ConfirmationIdError::TooLarge),
);
assert!(
generate("33448155882687086284384456622182339279486245740110381!")
.is_err_and(|err| err == ConfirmationIdError::InvalidCharacter),
);
assert!(
generate("334481558826870862843844566221823392794862457401103811")
.is_err_and(|err| err == ConfirmationIdError::InvalidCheckDigit),
);
}
}

63
umskt/src/crypto.rs Normal file
View file

@ -0,0 +1,63 @@
use anyhow::Result;
use openssl::{
bn::{BigNum, BigNumContext},
ec::{EcGroup, EcPoint},
};
pub struct EllipticCurve {
pub curve: EcGroup,
pub gen_point: EcPoint,
pub pub_point: EcPoint,
}
pub struct PrivateKey {
pub gen_order: BigNum,
pub private_key: BigNum,
}
impl PrivateKey {
pub fn new(gen_order: &str, private_key: &str) -> Result<Self> {
let gen_order = BigNum::from_dec_str(gen_order)?;
let private_key = &gen_order - &BigNum::from_dec_str(private_key)?;
Ok(Self {
gen_order,
private_key,
})
}
}
impl EllipticCurve {
pub fn new(
p: &str,
a: &str,
b: &str,
generator_x: &str,
generator_y: &str,
public_key_x: &str,
public_key_y: &str,
) -> Result<Self> {
let mut context = BigNumContext::new()?;
let p = BigNum::from_dec_str(p)?;
let a = BigNum::from_dec_str(a)?;
let b = BigNum::from_dec_str(b)?;
let generator_x = BigNum::from_dec_str(generator_x)?;
let generator_y = BigNum::from_dec_str(generator_y)?;
let public_key_x = BigNum::from_dec_str(public_key_x)?;
let public_key_y = BigNum::from_dec_str(public_key_y)?;
let curve = EcGroup::from_components(p, a, b, &mut context)?;
let mut gen_point = EcPoint::new(&curve)?;
gen_point.set_affine_coordinates_gfp(&curve, &generator_x, &generator_y, &mut context)?;
let mut pub_point = EcPoint::new(&curve)?;
pub_point.set_affine_coordinates_gfp(&curve, &public_key_x, &public_key_y, &mut context)?;
Ok(Self {
curve,
gen_point,
pub_point,
})
}
}

67
umskt/src/key.rs Normal file
View file

@ -0,0 +1,67 @@
use std::collections::VecDeque;
use anyhow::{anyhow, Result};
use openssl::bn::BigNum;
const PK_LENGTH: usize = 25;
/// The allowed character set in a product key.
pub const KEY_CHARSET: [char; 24] = [
'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'M', 'P', 'Q', 'R', 'T', 'V', 'W', 'X', 'Y', '2', '3',
'4', '6', '7', '8', '9',
];
pub(crate) fn base24_decode(cd_key: &str) -> Result<Vec<u8>> {
let decoded_key: Vec<u8> = cd_key
.chars()
.filter_map(|c| KEY_CHARSET.iter().position(|&x| x == c).map(|i| i as u8))
.collect();
let mut y = BigNum::from_u32(0).unwrap();
for i in decoded_key {
y.mul_word((PK_LENGTH - 1) as u32).unwrap();
y.add_word(i.into()).unwrap();
}
Ok(y.to_vec())
}
pub(crate) fn base24_encode(byte_seq: &[u8]) -> Result<String> {
let mut z = BigNum::from_slice(byte_seq).unwrap();
let mut out: VecDeque<char> = VecDeque::new();
(0..=24).for_each(|_| out.push_front(KEY_CHARSET[z.div_word(24).unwrap() as usize]));
Ok(out.iter().collect())
}
pub(crate) fn strip_key(in_key: &str) -> Result<String> {
let out_key: String = in_key
.chars()
.filter_map(|c| {
let c = c.to_ascii_uppercase();
if KEY_CHARSET.into_iter().any(|x| x == c) {
Some(c)
} else {
None
}
})
.collect();
if out_key.len() == PK_LENGTH {
Ok(out_key)
} else {
Err(anyhow!("Invalid key length"))
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_base24() {
let input = "JTW3TJ7PFJ7V9CCMX84V9PFT8";
let unbase24 = super::base24_decode(input).unwrap();
println!("{:?}", unbase24);
let base24 = super::base24_encode(&unbase24).unwrap();
println!("{}", base24);
assert_eq!(input, base24);
}
}

6
umskt/src/lib.rs Normal file
View file

@ -0,0 +1,6 @@
pub mod bink1998;
pub mod bink2002;
pub mod confid;
pub mod crypto;
mod key;
mod math;

11
umskt/src/math.rs Normal file
View file

@ -0,0 +1,11 @@
pub(crate) fn bitmask(n: u64) -> u64 {
(1 << n) - 1
}
pub(crate) fn next_sn_bits(field: u64, n: u32, offset: u32) -> u64 {
(field >> offset) & ((1u64 << n) - 1)
}
pub(crate) fn by_dword(n: &[u8]) -> u32 {
(n[0] as u32) | (n[1] as u32) << 8 | (n[2] as u32) << 16 | (n[3] as u32) << 24
}