Redesign lib public interface
This commit is contained in:
parent
83bfa98a38
commit
61d875757d
7 changed files with 603 additions and 562 deletions
|
@ -2,24 +2,20 @@ use std::{fs::File, io::BufReader, path::Path};
|
|||
|
||||
use anyhow::{anyhow, Result};
|
||||
use clap::Parser;
|
||||
use openssl::{
|
||||
bn::{BigNum, MsbOption},
|
||||
ec::{EcGroup, EcPoint},
|
||||
rand::rand_bytes,
|
||||
};
|
||||
use serde_json::{from_reader, from_str};
|
||||
|
||||
use umskt::{
|
||||
bink1998, bink2002, confid, crypto::initialize_elliptic_curve, key::P_KEY_CHARSET, PK_LENGTH,
|
||||
bink1998, bink2002, confid,
|
||||
crypto::{EllipticCurve, PrivateKey},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
Bink1998Generate,
|
||||
Bink2002Generate,
|
||||
ConfirmationId,
|
||||
Bink1998Validate,
|
||||
Bink2002Validate,
|
||||
ConfirmationId,
|
||||
}
|
||||
|
||||
impl Default for Mode {
|
||||
|
@ -37,7 +33,7 @@ pub struct Options {
|
|||
|
||||
/// Number of keys to generate
|
||||
#[arg(short = 'n', long = "number", default_value = "1")]
|
||||
num_keys: i32,
|
||||
num_keys: u64,
|
||||
|
||||
/// Specify which keys file to load
|
||||
#[arg(short = 'f', long = "file")]
|
||||
|
@ -69,12 +65,15 @@ pub struct Options {
|
|||
|
||||
pub struct Cli {
|
||||
options: Options,
|
||||
private_key: BigNum,
|
||||
gen_order: BigNum,
|
||||
gen_point: EcPoint,
|
||||
pub_point: EcPoint,
|
||||
e_curve: EcGroup,
|
||||
count: u32,
|
||||
p: String,
|
||||
a: String,
|
||||
b: String,
|
||||
gx: String,
|
||||
gy: String,
|
||||
kx: String,
|
||||
ky: String,
|
||||
n: String,
|
||||
k: String,
|
||||
}
|
||||
|
||||
impl Cli {
|
||||
|
@ -85,11 +84,11 @@ impl Cli {
|
|||
let bink = &keys["BINK"][&options.binkid];
|
||||
// We cannot produce a valid key without knowing the private key k. The reason for this is that
|
||||
// we need the result of the function K(x; y) = kG(x; y).
|
||||
let private_key = BigNum::from_dec_str(bink["priv"].as_str().unwrap()).unwrap();
|
||||
let private_key = bink["priv"].as_str().unwrap();
|
||||
|
||||
// We can, however, validate any given key using the available public key: {p, a, b, G, K}.
|
||||
// genOrder the order of the generator G, a value we have to reverse -> Schoof's Algorithm.
|
||||
let gen_order = BigNum::from_dec_str(bink["n"].as_str().unwrap()).unwrap();
|
||||
let gen_order = bink["n"].as_str().unwrap();
|
||||
|
||||
let p = bink["p"].as_str().unwrap();
|
||||
let a = bink["a"].as_str().unwrap();
|
||||
|
@ -98,8 +97,6 @@ impl Cli {
|
|||
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 n = bink["n"].as_str().unwrap();
|
||||
let k = bink["priv"].as_str().unwrap();
|
||||
|
||||
if options.verbose {
|
||||
println!("-----------------------------------------------------------");
|
||||
|
@ -115,21 +112,22 @@ impl Cli {
|
|||
println!("Gy: {gy}");
|
||||
println!("Kx: {kx}");
|
||||
println!("Ky: {ky}");
|
||||
println!(" n: {n}");
|
||||
println!(" k: {k}");
|
||||
println!(" n: {gen_order}");
|
||||
println!(" k: {private_key}");
|
||||
println!();
|
||||
}
|
||||
|
||||
let (e_curve, gen_point, pub_point) = initialize_elliptic_curve(p, a, b, gx, gy, kx, ky);
|
||||
|
||||
Ok(Self {
|
||||
options,
|
||||
private_key,
|
||||
gen_order,
|
||||
gen_point,
|
||||
pub_point,
|
||||
e_curve,
|
||||
count: 0,
|
||||
p: p.to_owned(),
|
||||
a: a.to_owned(),
|
||||
b: b.to_owned(),
|
||||
gx: gx.to_owned(),
|
||||
gy: gy.to_owned(),
|
||||
kx: kx.to_owned(),
|
||||
ky: ky.to_owned(),
|
||||
n: gen_order.to_owned(),
|
||||
k: private_key.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
|
@ -205,134 +203,71 @@ impl Cli {
|
|||
match self.options.application_mode {
|
||||
Mode::Bink1998Generate => self.bink1998_generate(),
|
||||
Mode::Bink2002Generate => self.bink2002_generate(),
|
||||
Mode::ConfirmationId => self.confirmation_id(),
|
||||
Mode::Bink1998Validate => self.bink1998_validate(),
|
||||
Mode::Bink2002Validate => self.bink2002_validate(),
|
||||
Mode::ConfirmationId => self.confirmation_id(),
|
||||
}
|
||||
}
|
||||
|
||||
fn bink1998_generate(&mut self) -> Result<()> {
|
||||
let mut n_raw = self.options.channel_id * 1_000_000; // <- change
|
||||
|
||||
let mut bn_rand = BigNum::new()?;
|
||||
bn_rand.rand(19, MsbOption::MAYBE_ZERO, false)?;
|
||||
|
||||
let o_raw: u32 = u32::from_be_bytes(bn_rand.to_vec_padded(4)?.try_into().unwrap());
|
||||
n_raw += o_raw % 999999;
|
||||
|
||||
if self.options.verbose {
|
||||
println!("> PID: {n_raw:09}");
|
||||
}
|
||||
|
||||
let private_key = &self.gen_order - &self.private_key;
|
||||
|
||||
let upgrade = false;
|
||||
let curve = EllipticCurve::new(
|
||||
&self.p, &self.a, &self.b, &self.gx, &self.gy, &self.kx, &self.ky,
|
||||
)?;
|
||||
let private_key = PrivateKey::new(&self.n, &self.k)?;
|
||||
|
||||
for _ in 0..self.options.num_keys {
|
||||
let p_key = bink1998::generate(
|
||||
&self.e_curve,
|
||||
&self.gen_point,
|
||||
&self.gen_order,
|
||||
let product_key = bink1998::ProductKey::new(
|
||||
&curve,
|
||||
&private_key,
|
||||
n_raw,
|
||||
upgrade,
|
||||
self.options.channel_id,
|
||||
None,
|
||||
None,
|
||||
)?;
|
||||
Cli::print_key(&p_key);
|
||||
|
||||
if bink1998::verify(
|
||||
&self.e_curve,
|
||||
&self.gen_point,
|
||||
&self.pub_point,
|
||||
&p_key,
|
||||
self.options.verbose,
|
||||
)? {
|
||||
self.count += 1;
|
||||
}
|
||||
println!("{product_key}");
|
||||
}
|
||||
|
||||
println!("Success count: {}/{}", self.count, self.options.num_keys);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn bink2002_generate(&mut self) -> Result<()> {
|
||||
let p_channel_id = self.options.channel_id;
|
||||
|
||||
if self.options.verbose {
|
||||
println!("> Channel ID: {p_channel_id:03}");
|
||||
}
|
||||
let curve = EllipticCurve::new(
|
||||
&self.p, &self.a, &self.b, &self.gx, &self.gy, &self.kx, &self.ky,
|
||||
)?;
|
||||
let private_key = PrivateKey::new(&self.n, &self.k)?;
|
||||
|
||||
for _ in 0..self.options.num_keys {
|
||||
let mut p_auth_info_bytes = [0_u8; 4];
|
||||
rand_bytes(&mut p_auth_info_bytes)?;
|
||||
let p_auth_info = u32::from_ne_bytes(p_auth_info_bytes) & ((1 << 10) - 1);
|
||||
|
||||
if self.options.verbose {
|
||||
println!("> AuthInfo: {p_auth_info}");
|
||||
}
|
||||
|
||||
let p_key = bink2002::generate(
|
||||
&self.e_curve,
|
||||
&self.gen_point,
|
||||
&self.gen_order,
|
||||
&self.private_key,
|
||||
p_channel_id,
|
||||
p_auth_info,
|
||||
false,
|
||||
let product_key = bink2002::ProductKey::new(
|
||||
&curve,
|
||||
&private_key,
|
||||
self.options.channel_id,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)?;
|
||||
Cli::print_key(&p_key);
|
||||
println!("\n");
|
||||
|
||||
if bink2002::verify(
|
||||
&self.e_curve,
|
||||
&self.gen_point,
|
||||
&self.pub_point,
|
||||
&p_key,
|
||||
self.options.verbose,
|
||||
)? {
|
||||
self.count += 1;
|
||||
}
|
||||
println!("{product_key}");
|
||||
}
|
||||
|
||||
println!("Success count: {}/{}", self.count, self.options.num_keys);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn bink1998_validate(&mut self) -> Result<()> {
|
||||
let Ok(key) = Self::strip_key(self.options.key_to_check.as_ref().unwrap()) else {
|
||||
return Err(anyhow!("Product key is in an incorrect format!"));
|
||||
};
|
||||
|
||||
Self::print_key(&key);
|
||||
if !bink1998::verify(
|
||||
&self.e_curve,
|
||||
&self.gen_point,
|
||||
&self.pub_point,
|
||||
&key,
|
||||
self.options.verbose,
|
||||
)? {
|
||||
return Err(anyhow!("Product key is invalid! Wrong BINK ID?"));
|
||||
}
|
||||
let curve = EllipticCurve::new(
|
||||
&self.p, &self.a, &self.b, &self.gx, &self.gy, &self.kx, &self.ky,
|
||||
)?;
|
||||
|
||||
let product_key =
|
||||
bink1998::ProductKey::from_key(&curve, self.options.key_to_check.as_ref().unwrap())?;
|
||||
println!("{product_key}");
|
||||
println!("Key validated successfully!");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn bink2002_validate(&mut self) -> Result<()> {
|
||||
let Ok(key) = Self::strip_key(self.options.key_to_check.as_ref().unwrap()) else {
|
||||
return Err(anyhow!("Product key is in an incorrect format!"));
|
||||
};
|
||||
|
||||
Self::print_key(&key);
|
||||
if !bink2002::verify(
|
||||
&self.e_curve,
|
||||
&self.gen_point,
|
||||
&self.pub_point,
|
||||
&key,
|
||||
self.options.verbose,
|
||||
)? {
|
||||
return Err(anyhow!("Product key is invalid! Wrong BINK ID?"));
|
||||
}
|
||||
let curve = EllipticCurve::new(
|
||||
&self.p, &self.a, &self.b, &self.gx, &self.gy, &self.kx, &self.ky,
|
||||
)?;
|
||||
|
||||
let product_key =
|
||||
bink2002::ProductKey::from_key(&curve, self.options.key_to_check.as_ref().unwrap())?;
|
||||
println!("{product_key}");
|
||||
println!("Key validated successfully!");
|
||||
Ok(())
|
||||
}
|
||||
|
@ -344,39 +279,4 @@ impl Cli {
|
|||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_key(pk: &str) {
|
||||
assert!(pk.len() >= PK_LENGTH);
|
||||
println!(
|
||||
"{}",
|
||||
pk.chars()
|
||||
.enumerate()
|
||||
.fold(String::new(), |mut acc: String, (i, c)| {
|
||||
if i > 0 && i % 5 == 0 {
|
||||
acc.push('-');
|
||||
}
|
||||
acc.push(c);
|
||||
acc
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
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 P_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"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
335
src/bink1998.rs
335
src/bink1998.rs
|
@ -1,4 +1,6 @@
|
|||
use anyhow::Result;
|
||||
use std::fmt::{Display, Formatter};
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
use bitreader::BitReader;
|
||||
use openssl::{
|
||||
bn::{BigNum, BigNumContext, MsbOption},
|
||||
|
@ -7,112 +9,171 @@ use openssl::{
|
|||
};
|
||||
|
||||
use crate::{
|
||||
crypto::bitmask,
|
||||
key::{base24_decode, base24_encode},
|
||||
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;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct ProductKey {
|
||||
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,
|
||||
serial: u32,
|
||||
hash: u32,
|
||||
signature: u64,
|
||||
}
|
||||
|
||||
pub fn verify(
|
||||
e_curve: &EcGroup,
|
||||
base_point: &EcPoint,
|
||||
public_key: &EcPoint,
|
||||
p_key: &str,
|
||||
verbose: bool,
|
||||
) -> Result<bool> {
|
||||
let mut num_context = BigNumContext::new()?;
|
||||
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
|
||||
}
|
||||
};
|
||||
|
||||
let p_raw = base24_decode(p_key);
|
||||
let product_key = unpack(&p_raw)?;
|
||||
// Default to upgrade=false
|
||||
let upgrade = upgrade.unwrap_or(false);
|
||||
|
||||
let p_data = product_key.serial << 1 | product_key.upgrade as u32;
|
||||
// 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 * 1_000_000 + sequence,
|
||||
upgrade,
|
||||
)?;
|
||||
|
||||
if verbose {
|
||||
println!("Validation results:");
|
||||
println!(" Upgrade: {}", product_key.upgrade);
|
||||
println!(" Serial: {}", product_key.serial);
|
||||
println!(" Hash: {}", product_key.hash);
|
||||
println!(" Signature: {}", product_key.signature);
|
||||
println!();
|
||||
// Make sure the key is valid
|
||||
product_key.verify(&curve.curve, &curve.gen_point, &curve.pub_point)?;
|
||||
|
||||
// Ship it
|
||||
Ok(product_key)
|
||||
}
|
||||
|
||||
let e = BigNum::from_u32(product_key.hash)?;
|
||||
let s = BigNum::from_slice(&product_key.signature.to_be_bytes())?;
|
||||
let mut x = BigNum::new()?;
|
||||
let mut y = BigNum::new()?;
|
||||
pub fn from_key(curve: &EllipticCurve, key: &str) -> Result<Self> {
|
||||
let key = strip_key(key)?;
|
||||
let Ok(p_raw) = base24_decode(&key) else {
|
||||
bail!("Product key is in an incorrect format!")
|
||||
};
|
||||
let product_key = Self::from_packed(&p_raw)?;
|
||||
product_key.verify(&curve.curve, &curve.gen_point, &curve.pub_point)?;
|
||||
Ok(product_key)
|
||||
}
|
||||
|
||||
let mut t = EcPoint::new(e_curve)?;
|
||||
let mut p = EcPoint::new(e_curve)?;
|
||||
let mut p_2 = EcPoint::new(e_curve)?;
|
||||
fn generate(
|
||||
e_curve: &EcGroup,
|
||||
base_point: &EcPoint,
|
||||
gen_order: &BigNum,
|
||||
private_key: &BigNum,
|
||||
p_serial: u32,
|
||||
p_upgrade: bool,
|
||||
) -> Result<Self> {
|
||||
let mut num_context = BigNumContext::new().unwrap();
|
||||
|
||||
t.mul(e_curve, base_point, &s, &num_context)?;
|
||||
p.mul(e_curve, public_key, &e, &num_context)?;
|
||||
p_2.mul(e_curve, public_key, &e, &num_context)?;
|
||||
let mut c = BigNum::new()?;
|
||||
let mut s = BigNum::new()?;
|
||||
let mut s_2 = BigNum::new()?;
|
||||
let mut x = BigNum::new()?;
|
||||
let mut y = BigNum::new()?;
|
||||
|
||||
p.add(e_curve, &t, &p_2, &mut num_context)?;
|
||||
let p_data = p_serial << 1 | p_upgrade as u32;
|
||||
|
||||
p.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?;
|
||||
let product_key = loop {
|
||||
let mut r = EcPoint::new(e_curve)?;
|
||||
|
||||
let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH];
|
||||
// Generate a random number c consisting of 384 bits without any constraints.
|
||||
c.rand(FIELD_BITS, MsbOption::MAYBE_ZERO, false)?;
|
||||
|
||||
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();
|
||||
// Pick a random derivative of the base point on the elliptic curve.
|
||||
// R = cG;
|
||||
r.mul(e_curve, base_point, &c, &num_context)?;
|
||||
|
||||
msg_buffer[0..4].copy_from_slice(&p_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);
|
||||
// Acquire its coordinates.
|
||||
// x = R.x; y = R.y;
|
||||
r.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?;
|
||||
|
||||
let msg_digest = sha1(&msg_buffer);
|
||||
let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH];
|
||||
|
||||
let hash: u32 =
|
||||
u32::from_le_bytes(msg_digest[0..4].try_into().unwrap()) >> 4 & bitmask(28) as u32;
|
||||
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();
|
||||
|
||||
Ok(hash == product_key.hash)
|
||||
}
|
||||
msg_buffer[0..4].copy_from_slice(&p_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);
|
||||
|
||||
pub fn generate(
|
||||
e_curve: &EcGroup,
|
||||
base_point: &EcPoint,
|
||||
gen_order: &BigNum,
|
||||
private_key: &BigNum,
|
||||
p_serial: u32,
|
||||
p_upgrade: bool,
|
||||
) -> Result<String> {
|
||||
let mut num_context = BigNumContext::new().unwrap();
|
||||
let msg_digest = sha1(&msg_buffer);
|
||||
|
||||
let mut c = BigNum::new()?;
|
||||
let mut s = BigNum::new()?;
|
||||
let mut s_2 = BigNum::new()?;
|
||||
let mut x = BigNum::new()?;
|
||||
let mut y = BigNum::new()?;
|
||||
let p_hash: u32 =
|
||||
u32::from_le_bytes(msg_digest[0..4].try_into().unwrap()) >> 4 & bitmask(28) as u32;
|
||||
|
||||
let p_data = p_serial << 1 | p_upgrade as u32;
|
||||
s_2.copy_from_slice(&private_key.to_vec())?;
|
||||
s_2.mul_word(p_hash)?;
|
||||
|
||||
let p_raw = loop {
|
||||
let mut r = EcPoint::new(e_curve)?;
|
||||
s.mod_add(&s_2, &c, gen_order, &mut num_context)?;
|
||||
|
||||
// Generate a random number c consisting of 384 bits without any constraints.
|
||||
c.rand(FIELD_BITS, MsbOption::MAYBE_ZERO, false)?;
|
||||
let p_signature = u64::from_be_bytes(s.to_vec_padded(8)?.try_into().unwrap());
|
||||
|
||||
// Pick a random derivative of the base point on the elliptic curve.
|
||||
// R = cG;
|
||||
r.mul(e_curve, base_point, &c, &num_context)?;
|
||||
if p_signature <= bitmask(55) {
|
||||
break Self {
|
||||
upgrade: p_upgrade,
|
||||
serial: p_serial,
|
||||
hash: p_hash,
|
||||
signature: p_signature,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// Acquire its coordinates.
|
||||
// x = R.x; y = R.y;
|
||||
r.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?;
|
||||
Ok(product_key)
|
||||
}
|
||||
|
||||
fn verify(
|
||||
&self,
|
||||
e_curve: &EcGroup,
|
||||
base_point: &EcPoint,
|
||||
public_key: &EcPoint,
|
||||
) -> Result<bool> {
|
||||
let mut num_context = BigNumContext::new()?;
|
||||
|
||||
let p_data = self.serial << 1 | self.upgrade as u32;
|
||||
|
||||
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)?;
|
||||
let mut p_2 = EcPoint::new(e_curve)?;
|
||||
|
||||
t.mul(e_curve, base_point, &s, &num_context)?;
|
||||
p.mul(e_curve, public_key, &e, &num_context)?;
|
||||
p_2.mul(e_curve, public_key, &e, &num_context)?;
|
||||
|
||||
p.add(e_curve, &t, &p_2, &mut num_context)?;
|
||||
|
||||
p.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?;
|
||||
|
||||
let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH];
|
||||
|
||||
|
@ -127,65 +188,61 @@ pub fn generate(
|
|||
|
||||
let msg_digest = sha1(&msg_buffer);
|
||||
|
||||
let p_hash: u32 =
|
||||
let hash: u32 =
|
||||
u32::from_le_bytes(msg_digest[0..4].try_into().unwrap()) >> 4 & bitmask(28) as u32;
|
||||
|
||||
s_2.copy_from_slice(&private_key.to_vec())?;
|
||||
s_2.mul_word(p_hash)?;
|
||||
Ok(hash == self.hash)
|
||||
}
|
||||
|
||||
s.mod_add(&s_2, &c, gen_order, &mut num_context)?;
|
||||
fn from_packed(p_raw: &[u8]) -> Result<Self> {
|
||||
let mut reader = BitReader::new(p_raw);
|
||||
// The signature length is unknown, but everything else is, so we can calculate it
|
||||
let signature_length_bits = (p_raw.len() * 8) as u8 - EVERYTHING_ELSE;
|
||||
|
||||
let p_signature = u64::from_be_bytes(s.to_vec_padded(8)?.try_into().unwrap());
|
||||
let p_signature = reader.read_u64(signature_length_bits)?;
|
||||
let p_hash = reader.read_u32(HASH_LENGTH_BITS)?;
|
||||
let p_serial = reader.read_u32(SERIAL_LENGTH_BITS)?;
|
||||
let p_upgrade = reader.read_bool()?;
|
||||
|
||||
if p_signature <= bitmask(55) {
|
||||
break pack(ProductKey {
|
||||
upgrade: p_upgrade,
|
||||
serial: p_serial,
|
||||
hash: p_hash,
|
||||
signature: p_signature,
|
||||
Ok(Self {
|
||||
upgrade: p_upgrade,
|
||||
serial: p_serial,
|
||||
hash: p_hash,
|
||||
signature: p_signature,
|
||||
})
|
||||
}
|
||||
|
||||
fn pack(&self) -> Vec<u8> {
|
||||
let mut p_raw: u128 = 0;
|
||||
|
||||
p_raw |= (self.signature as u128) << EVERYTHING_ELSE;
|
||||
p_raw |= (self.hash as u128) << (SERIAL_LENGTH_BITS + UPGRADE_LENGTH_BITS);
|
||||
p_raw |= (self.serial as u128) << UPGRADE_LENGTH_BITS;
|
||||
p_raw |= self.upgrade as u128;
|
||||
|
||||
p_raw
|
||||
.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
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
Ok(base24_encode(&p_raw))
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
fn unpack(p_raw: &[u8]) -> Result<ProductKey> {
|
||||
let mut reader = BitReader::new(p_raw);
|
||||
// The signature length is unknown, but everything else is, so we can calculate it
|
||||
let signature_length_bits = (p_raw.len() * 8) as u8 - EVERYTHING_ELSE;
|
||||
|
||||
let p_signature = reader.read_u64(signature_length_bits)?;
|
||||
let p_hash = reader.read_u32(HASH_LENGTH_BITS)?;
|
||||
let p_serial = reader.read_u32(SERIAL_LENGTH_BITS)?;
|
||||
let p_upgrade = reader.read_bool()?;
|
||||
|
||||
Ok(ProductKey {
|
||||
upgrade: p_upgrade,
|
||||
serial: p_serial,
|
||||
hash: p_hash,
|
||||
signature: p_signature,
|
||||
})
|
||||
}
|
||||
|
||||
fn pack(p_key: ProductKey) -> Vec<u8> {
|
||||
let mut p_raw: u128 = 0;
|
||||
|
||||
p_raw |= (p_key.signature as u128) << EVERYTHING_ELSE;
|
||||
p_raw |= (p_key.hash as u128) << (SERIAL_LENGTH_BITS + UPGRADE_LENGTH_BITS);
|
||||
p_raw |= (p_key.serial as u128) << UPGRADE_LENGTH_BITS;
|
||||
p_raw |= p_key.upgrade as u128;
|
||||
|
||||
p_raw
|
||||
.to_be_bytes()
|
||||
.into_iter()
|
||||
.skip_while(|&x| x == 0)
|
||||
.collect()
|
||||
write!(f, "{}", key)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
@ -194,7 +251,7 @@ mod tests {
|
|||
|
||||
use serde_json::from_reader;
|
||||
|
||||
use crate::crypto::initialize_elliptic_curve;
|
||||
use crate::crypto::EllipticCurve;
|
||||
|
||||
#[test]
|
||||
fn verify_test() {
|
||||
|
@ -218,35 +275,21 @@ mod tests {
|
|||
let kx = bink["pub"]["x"].as_str().unwrap();
|
||||
let ky = bink["pub"]["y"].as_str().unwrap();
|
||||
|
||||
let (e_curve, gen_point, pub_point) = initialize_elliptic_curve(p, a, b, gx, gy, kx, ky);
|
||||
let curve = EllipticCurve::new(p, a, b, gx, gy, kx, ky).unwrap();
|
||||
|
||||
assert!(super::verify(&e_curve, &gen_point, &pub_point, product_key, true).unwrap());
|
||||
assert!(!super::verify(
|
||||
&e_curve,
|
||||
&gen_point,
|
||||
&pub_point,
|
||||
"11111-R6BG2-39J83-RYKHF-W47TT",
|
||||
true
|
||||
)
|
||||
.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 p_key = super::ProductKey {
|
||||
let key = super::ProductKey {
|
||||
upgrade: false,
|
||||
serial: 640010550,
|
||||
hash: 39185432,
|
||||
signature: 6939952665262054,
|
||||
};
|
||||
|
||||
let p_raw = super::pack(p_key);
|
||||
|
||||
assert_eq!(
|
||||
p_raw,
|
||||
vec![
|
||||
0xC5, 0x3E, 0xCD, 0x2A, 0xF7, 0xBF, 0x31, 0x2A, 0xF6, 0x0C, 0x4C, 0x4B, 0x92, 0x6C
|
||||
]
|
||||
);
|
||||
assert_eq!(key.to_string(), "D9924-R6BG2-39J83-RYKHF-W47TT");
|
||||
}
|
||||
}
|
||||
|
|
472
src/bink2002.rs
472
src/bink2002.rs
|
@ -1,22 +1,33 @@
|
|||
use anyhow::Result;
|
||||
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::{bitmask, by_dword, next_sn_bits},
|
||||
key::{base24_decode, base24_encode},
|
||||
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;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct ProductKey {
|
||||
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,
|
||||
|
@ -24,117 +35,231 @@ struct ProductKey {
|
|||
auth_info: u32,
|
||||
}
|
||||
|
||||
pub fn verify(
|
||||
e_curve: &EcGroup,
|
||||
base_point: &EcPoint,
|
||||
public_key: &EcPoint,
|
||||
cd_key: &str,
|
||||
verbose: bool,
|
||||
) -> Result<bool> {
|
||||
let mut num_context = BigNumContext::new()?;
|
||||
impl ProductKey {
|
||||
pub fn new(
|
||||
curve: &EllipticCurve,
|
||||
private_key: &PrivateKey,
|
||||
channel_id: u32,
|
||||
sequence: Option<u32>,
|
||||
auth_info: 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
|
||||
}
|
||||
};
|
||||
|
||||
let b_key = base24_decode(cd_key);
|
||||
let product_key = unpack(&b_key)?;
|
||||
// Generate random auth info if none supplied
|
||||
let auth_info = match auth_info {
|
||||
Some(auth_info) => auth_info,
|
||||
None => {
|
||||
let mut p_auth_info_bytes = [0_u8; 4];
|
||||
rand_bytes(&mut p_auth_info_bytes)?;
|
||||
u32::from_ne_bytes(p_auth_info_bytes) & ((1 << 10) - 1)
|
||||
}
|
||||
};
|
||||
|
||||
let p_data = product_key.channel_id << 1 | product_key.upgrade as u32;
|
||||
// Default to upgrade=false
|
||||
let upgrade = upgrade.unwrap_or(false);
|
||||
|
||||
if verbose {
|
||||
println!("Validation results:");
|
||||
println!(" Upgrade: {}", product_key.upgrade);
|
||||
println!("Channel ID: {}", product_key.channel_id);
|
||||
println!(" Hash: {}", product_key.hash);
|
||||
println!(" Signature: {}", product_key.signature);
|
||||
println!(" AuthInfo: {}", product_key.auth_info);
|
||||
println!();
|
||||
// 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 * 1_000_000 + sequence,
|
||||
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)
|
||||
}
|
||||
|
||||
let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH];
|
||||
pub fn from_key(curve: &EllipticCurve, key: &str) -> Result<Self> {
|
||||
let key = strip_key(key)?;
|
||||
let Ok(p_raw) = base24_decode(&key) else {
|
||||
bail!("Product key is in an incorrect format!")
|
||||
};
|
||||
let product_key = Self::from_packed(&p_raw)?;
|
||||
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)
|
||||
}
|
||||
|
||||
msg_buffer[0x00] = 0x5D;
|
||||
msg_buffer[0x01] = (p_data & 0x00FF) as u8;
|
||||
msg_buffer[0x02] = ((p_data & 0xFF00) >> 8) as u8;
|
||||
msg_buffer[0x03] = (product_key.hash & 0x000000FF) as u8;
|
||||
msg_buffer[0x04] = ((product_key.hash & 0x0000FF00) >> 8) as u8;
|
||||
msg_buffer[0x05] = ((product_key.hash & 0x00FF0000) >> 16) as u8;
|
||||
msg_buffer[0x06] = ((product_key.hash & 0xFF000000) >> 24) as u8;
|
||||
msg_buffer[0x07] = (product_key.auth_info & 0x00FF) as u8;
|
||||
msg_buffer[0x08] = ((product_key.auth_info & 0xFF00) >> 8) as u8;
|
||||
msg_buffer[0x09] = 0x00;
|
||||
msg_buffer[0x0A] = 0x00;
|
||||
fn generate(
|
||||
e_curve: &EcGroup,
|
||||
base_point: &EcPoint,
|
||||
gen_order: &BigNum,
|
||||
private_key: &BigNum,
|
||||
p_channel_id: u32,
|
||||
p_auth_info: u32,
|
||||
p_upgrade: bool,
|
||||
) -> Result<Self> {
|
||||
let mut num_context = BigNumContext::new().unwrap();
|
||||
|
||||
let msg_digest = sha1(&msg_buffer[..=0x0A]);
|
||||
let mut c = BigNum::new()?;
|
||||
let mut x = BigNum::new()?;
|
||||
let mut y = BigNum::new()?;
|
||||
|
||||
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 p_data = p_channel_id << 1 | p_upgrade as u32;
|
||||
|
||||
let e = BigNum::from_slice(&i_signature.to_be_bytes())?;
|
||||
let s = BigNum::from_slice(&product_key.signature.to_be_bytes())?;
|
||||
let mut no_square = false;
|
||||
let key = loop {
|
||||
let mut r = EcPoint::new(e_curve)?;
|
||||
|
||||
let mut x = BigNum::new()?;
|
||||
let mut y = BigNum::new()?;
|
||||
c.rand(FIELD_BITS, MsbOption::MAYBE_ZERO, false)?;
|
||||
|
||||
let mut p = EcPoint::new(e_curve)?;
|
||||
let mut t = EcPoint::new(e_curve)?;
|
||||
r.mul(e_curve, base_point, &c, &num_context)?;
|
||||
|
||||
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)?;
|
||||
r.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?;
|
||||
|
||||
p.add(e_curve, &t, &p_2, &mut num_context)?;
|
||||
let p_2 = p.to_owned(e_curve)?;
|
||||
let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH];
|
||||
|
||||
p.mul(e_curve, &p_2, &s, &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();
|
||||
|
||||
p.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?;
|
||||
msg_buffer[0x00] = 0x79;
|
||||
msg_buffer[0x01] = (p_data & 0x00FF) as u8;
|
||||
msg_buffer[0x02] = ((p_data & 0xFF00) >> 8) as u8;
|
||||
|
||||
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[3..3 + FIELD_BYTES].copy_from_slice(&x_bin);
|
||||
msg_buffer[3 + FIELD_BYTES..3 + FIELD_BYTES * 2].copy_from_slice(&y_bin);
|
||||
|
||||
msg_buffer[0x00] = 0x79;
|
||||
msg_buffer[0x01] = (p_data & 0x00FF) as u8;
|
||||
msg_buffer[0x02] = ((p_data & 0xFF00) >> 8) as u8;
|
||||
let msg_digest = sha1(&msg_buffer);
|
||||
|
||||
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 p_hash: u32 = by_dword(&msg_digest[0..4]) & bitmask(31) as u32;
|
||||
|
||||
let msg_digest = sha1(&msg_buffer);
|
||||
msg_buffer[0x00] = 0x5D;
|
||||
msg_buffer[0x01] = (p_data & 0x00FF) as u8;
|
||||
msg_buffer[0x02] = ((p_data & 0xFF00) >> 8) as u8;
|
||||
msg_buffer[0x03] = (p_hash & 0x000000FF) as u8;
|
||||
msg_buffer[0x04] = ((p_hash & 0x0000FF00) >> 8) as u8;
|
||||
msg_buffer[0x05] = ((p_hash & 0x00FF0000) >> 16) as u8;
|
||||
msg_buffer[0x06] = ((p_hash & 0xFF000000) >> 24) as u8;
|
||||
msg_buffer[0x07] = (p_auth_info & 0x00FF) as u8;
|
||||
msg_buffer[0x08] = ((p_auth_info & 0xFF00) >> 8) as u8;
|
||||
msg_buffer[0x09] = 0x00;
|
||||
msg_buffer[0x0A] = 0x00;
|
||||
|
||||
let hash: u32 = by_dword(&msg_digest[0..4]) & bitmask(31) as u32;
|
||||
let msg_digest = sha1(&msg_buffer[..=0x0A]);
|
||||
|
||||
Ok(hash == product_key.hash)
|
||||
}
|
||||
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;
|
||||
|
||||
pub fn generate(
|
||||
e_curve: &EcGroup,
|
||||
base_point: &EcPoint,
|
||||
gen_order: &BigNum,
|
||||
private_key: &BigNum,
|
||||
p_channel_id: u32,
|
||||
p_auth_info: u32,
|
||||
p_upgrade: bool,
|
||||
) -> Result<String> {
|
||||
let mut num_context = BigNumContext::new().unwrap();
|
||||
let mut e = BigNum::from_slice(&i_signature.to_be_bytes())?;
|
||||
|
||||
let mut c = BigNum::new()?;
|
||||
let mut x = BigNum::new()?;
|
||||
let mut y = BigNum::new()?;
|
||||
let e_2 = e.to_owned()?;
|
||||
e.mod_mul(&e_2, private_key, gen_order, &mut num_context)?;
|
||||
|
||||
let p_data = p_channel_id << 1 | p_upgrade as u32;
|
||||
let mut s = e.to_owned()?;
|
||||
|
||||
let mut no_square = false;
|
||||
let p_raw: Vec<u8> = loop {
|
||||
let mut r = EcPoint::new(e_curve)?;
|
||||
let s_2 = s.to_owned()?;
|
||||
s.mod_sqr(&s_2, gen_order, &mut num_context)?;
|
||||
|
||||
c.rand(FIELD_BITS, MsbOption::MAYBE_ZERO, false)?;
|
||||
let c_2 = c.to_owned()?;
|
||||
c.lshift(&c_2, 2)?;
|
||||
|
||||
r.mul(e_curve, base_point, &c, &num_context)?;
|
||||
s = &s + &c;
|
||||
|
||||
r.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?;
|
||||
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 p_signature = u64::from_be_bytes(s.to_vec_padded(8)?.try_into().unwrap());
|
||||
|
||||
let product_key = Self {
|
||||
upgrade: p_upgrade,
|
||||
channel_id: p_channel_id,
|
||||
hash: p_hash,
|
||||
signature: p_signature,
|
||||
auth_info: p_auth_info,
|
||||
};
|
||||
|
||||
if p_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 p_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] = (p_data & 0x00FF) as u8;
|
||||
msg_buffer[0x02] = ((p_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)?;
|
||||
|
@ -149,130 +274,75 @@ pub fn generate(
|
|||
|
||||
let msg_digest = sha1(&msg_buffer);
|
||||
|
||||
let p_hash: u32 = by_dword(&msg_digest[0..4]) & bitmask(31) as u32;
|
||||
let hash: u32 = by_dword(&msg_digest[0..4]) & bitmask(31) as u32;
|
||||
|
||||
msg_buffer[0x00] = 0x5D;
|
||||
msg_buffer[0x01] = (p_data & 0x00FF) as u8;
|
||||
msg_buffer[0x02] = ((p_data & 0xFF00) >> 8) as u8;
|
||||
msg_buffer[0x03] = (p_hash & 0x000000FF) as u8;
|
||||
msg_buffer[0x04] = ((p_hash & 0x0000FF00) >> 8) as u8;
|
||||
msg_buffer[0x05] = ((p_hash & 0x00FF0000) >> 16) as u8;
|
||||
msg_buffer[0x06] = ((p_hash & 0xFF000000) >> 24) as u8;
|
||||
msg_buffer[0x07] = (p_auth_info & 0x00FF) as u8;
|
||||
msg_buffer[0x08] = ((p_auth_info & 0xFF00) >> 8) as u8;
|
||||
msg_buffer[0x09] = 0x00;
|
||||
msg_buffer[0x0A] = 0x00;
|
||||
Ok(hash == self.hash)
|
||||
}
|
||||
|
||||
let msg_digest = sha1(&msg_buffer[..=0x0A]);
|
||||
fn from_packed(p_raw: &[u8]) -> Result<Self> {
|
||||
let mut reader = BitReader::new(p_raw);
|
||||
let auth_info_length_bits = (p_raw.len() * 8) as u8 - EVERYTHING_ELSE;
|
||||
|
||||
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 p_auth_info = reader.read_u32(auth_info_length_bits)?;
|
||||
let p_signature = reader.read_u64(SIGNATURE_LENGTH_BITS)?;
|
||||
let p_hash = reader.read_u32(HASH_LENGTH_BITS)?;
|
||||
let p_channel_id = reader.read_u32(CHANNEL_ID_LENGTH_BITS)?;
|
||||
let p_upgrade = reader.read_bool()?;
|
||||
|
||||
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 p_signature = u64::from_be_bytes(s.to_vec_padded(8)?.try_into().unwrap());
|
||||
|
||||
let product_key = ProductKey {
|
||||
Ok(Self {
|
||||
upgrade: p_upgrade,
|
||||
channel_id: p_channel_id,
|
||||
hash: p_hash,
|
||||
signature: p_signature,
|
||||
auth_info: p_auth_info,
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
if p_signature <= bitmask(62) && !no_square {
|
||||
break pack(product_key);
|
||||
}
|
||||
fn pack(&self) -> Vec<u8> {
|
||||
let mut p_raw: u128 = 0;
|
||||
|
||||
no_square = false;
|
||||
};
|
||||
p_raw |= (self.auth_info as u128)
|
||||
<< (SIGNATURE_LENGTH_BITS
|
||||
+ HASH_LENGTH_BITS
|
||||
+ CHANNEL_ID_LENGTH_BITS
|
||||
+ UPGRADE_LENGTH_BITS);
|
||||
p_raw |= (self.signature as u128)
|
||||
<< (HASH_LENGTH_BITS + CHANNEL_ID_LENGTH_BITS + UPGRADE_LENGTH_BITS);
|
||||
p_raw |= (self.hash as u128) << (CHANNEL_ID_LENGTH_BITS + UPGRADE_LENGTH_BITS);
|
||||
p_raw |= (self.channel_id as u128) << UPGRADE_LENGTH_BITS;
|
||||
p_raw |= self.upgrade as u128;
|
||||
|
||||
Ok(base24_encode(&p_raw))
|
||||
p_raw
|
||||
.to_be_bytes()
|
||||
.into_iter()
|
||||
.skip_while(|&x| x == 0)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
fn unpack(p_raw: &[u8]) -> Result<ProductKey> {
|
||||
let mut reader = BitReader::new(p_raw);
|
||||
let auth_info_length_bits = (p_raw.len() * 8) as u8 - EVERYTHING_ELSE;
|
||||
|
||||
let p_auth_info = reader.read_u32(auth_info_length_bits)?;
|
||||
let p_signature = reader.read_u64(SIGNATURE_LENGTH_BITS)?;
|
||||
let p_hash = reader.read_u32(HASH_LENGTH_BITS)?;
|
||||
let p_channel_id = reader.read_u32(CHANNEL_ID_LENGTH_BITS)?;
|
||||
let p_upgrade = reader.read_bool()?;
|
||||
|
||||
Ok(ProductKey {
|
||||
upgrade: p_upgrade,
|
||||
channel_id: p_channel_id,
|
||||
hash: p_hash,
|
||||
signature: p_signature,
|
||||
auth_info: p_auth_info,
|
||||
})
|
||||
}
|
||||
|
||||
fn pack(p_key: ProductKey) -> Vec<u8> {
|
||||
let mut p_raw: u128 = 0;
|
||||
|
||||
p_raw |= (p_key.auth_info as u128)
|
||||
<< (SIGNATURE_LENGTH_BITS
|
||||
+ HASH_LENGTH_BITS
|
||||
+ CHANNEL_ID_LENGTH_BITS
|
||||
+ UPGRADE_LENGTH_BITS);
|
||||
p_raw |= (p_key.signature as u128)
|
||||
<< (HASH_LENGTH_BITS + CHANNEL_ID_LENGTH_BITS + UPGRADE_LENGTH_BITS);
|
||||
p_raw |= (p_key.hash as u128) << (CHANNEL_ID_LENGTH_BITS + UPGRADE_LENGTH_BITS);
|
||||
p_raw |= (p_key.channel_id as u128) << UPGRADE_LENGTH_BITS;
|
||||
p_raw |= p_key.upgrade as u128;
|
||||
|
||||
p_raw
|
||||
.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 openssl::bn::{BigNum, BigNumContext};
|
||||
use serde_json::from_reader;
|
||||
|
||||
use crate::crypto::initialize_elliptic_curve;
|
||||
use crate::crypto::EllipticCurve;
|
||||
|
||||
#[test]
|
||||
fn verify_test() {
|
||||
|
@ -296,27 +366,9 @@ mod tests {
|
|||
let kx = bink["pub"]["x"].as_str().unwrap();
|
||||
let ky = bink["pub"]["y"].as_str().unwrap();
|
||||
|
||||
let (e_curve, gen_point, pub_point) = initialize_elliptic_curve(p, a, b, gx, gy, kx, ky);
|
||||
let curve = EllipticCurve::new(p, a, b, gx, gy, kx, ky).unwrap();
|
||||
|
||||
assert!(super::verify(&e_curve, &gen_point, &pub_point, product_key, true).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prime_test() {
|
||||
let mut ctx = BigNumContext::new().unwrap();
|
||||
let p = BigNum::from_dec_str("9759712359818460653").unwrap();
|
||||
let mut p2 = BigNum::new().unwrap();
|
||||
let _ = p2.sqr(&p, &mut ctx);
|
||||
println!("p2: {:?}", p2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqrt_test() {
|
||||
let mut ctx = BigNumContext::new().unwrap();
|
||||
let s = BigNum::from_dec_str("95251985346393225982548498694509186409").unwrap();
|
||||
let p = BigNum::from_dec_str("9362780380393422053").unwrap();
|
||||
let mut out = BigNum::new().unwrap();
|
||||
out.mod_sqrt(&s, &p, &mut ctx).unwrap();
|
||||
assert_eq!(out, BigNum::from_dec_str("8965848400968383453").unwrap());
|
||||
assert!(super::ProductKey::from_key(&curve, product_key).is_ok());
|
||||
assert!(super::ProductKey::from_key(&curve, "11111-YRGC8-4KYTG-C3FCC-JCFDY").is_err());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,49 +1,63 @@
|
|||
use anyhow::Result;
|
||||
use openssl::{
|
||||
bn::{BigNum, BigNumContext},
|
||||
ec::{EcGroup, EcPoint},
|
||||
};
|
||||
|
||||
pub fn initialize_elliptic_curve(
|
||||
p_sel: &str,
|
||||
a_sel: &str,
|
||||
b_sel: &str,
|
||||
generator_x_sel: &str,
|
||||
generator_y_sel: &str,
|
||||
public_key_x_sel: &str,
|
||||
public_key_y_sel: &str,
|
||||
) -> (EcGroup, EcPoint, EcPoint) {
|
||||
let mut context = BigNumContext::new().unwrap();
|
||||
|
||||
let p = BigNum::from_dec_str(p_sel).unwrap();
|
||||
let a = BigNum::from_dec_str(a_sel).unwrap();
|
||||
let b = BigNum::from_dec_str(b_sel).unwrap();
|
||||
let generator_x = BigNum::from_dec_str(generator_x_sel).unwrap();
|
||||
let generator_y = BigNum::from_dec_str(generator_y_sel).unwrap();
|
||||
|
||||
let public_key_x = BigNum::from_dec_str(public_key_x_sel).unwrap();
|
||||
let public_key_y = BigNum::from_dec_str(public_key_y_sel).unwrap();
|
||||
|
||||
let c_curve = EcGroup::from_components(p, a, b, &mut context).unwrap();
|
||||
|
||||
let mut gen_point = EcPoint::new(&c_curve).unwrap();
|
||||
let _ =
|
||||
gen_point.set_affine_coordinates_gfp(&c_curve, &generator_x, &generator_y, &mut context);
|
||||
|
||||
let mut pub_point = EcPoint::new(&c_curve).unwrap();
|
||||
let _ =
|
||||
pub_point.set_affine_coordinates_gfp(&c_curve, &public_key_x, &public_key_y, &mut context);
|
||||
|
||||
(c_curve, gen_point, pub_point)
|
||||
pub struct EllipticCurve {
|
||||
pub curve: EcGroup,
|
||||
pub gen_point: EcPoint,
|
||||
pub pub_point: EcPoint,
|
||||
}
|
||||
|
||||
pub fn bitmask(n: u64) -> u64 {
|
||||
(1 << n) - 1
|
||||
pub struct PrivateKey {
|
||||
pub gen_order: BigNum,
|
||||
pub private_key: BigNum,
|
||||
}
|
||||
|
||||
pub fn next_sn_bits(field: u64, n: u32, offset: u32) -> u64 {
|
||||
(field >> offset) & ((1u64 << n) - 1)
|
||||
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,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub 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
|
||||
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,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
32
src/key.rs
32
src/key.rs
|
@ -1,5 +1,6 @@
|
|||
use std::collections::VecDeque;
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use openssl::bn::BigNum;
|
||||
|
||||
use crate::PK_LENGTH;
|
||||
|
@ -10,7 +11,7 @@ pub const P_KEY_CHARSET: [char; 24] = [
|
|||
'4', '6', '7', '8', '9',
|
||||
];
|
||||
|
||||
pub fn base24_decode(cd_key: &str) -> Vec<u8> {
|
||||
pub(crate) fn base24_decode(cd_key: &str) -> Result<Vec<u8>> {
|
||||
let p_decoded_key: Vec<u8> = cd_key
|
||||
.chars()
|
||||
.filter_map(|c| P_KEY_CHARSET.iter().position(|&x| x == c).map(|i| i as u8))
|
||||
|
@ -23,14 +24,33 @@ pub fn base24_decode(cd_key: &str) -> Vec<u8> {
|
|||
y.add_word(i.into()).unwrap();
|
||||
}
|
||||
|
||||
y.to_vec()
|
||||
Ok(y.to_vec())
|
||||
}
|
||||
|
||||
pub fn base24_encode(byte_seq: &[u8]) -> String {
|
||||
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(P_KEY_CHARSET[z.div_word(24).unwrap() as usize]));
|
||||
out.iter().collect()
|
||||
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 P_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)]
|
||||
|
@ -38,9 +58,9 @@ mod tests {
|
|||
#[test]
|
||||
fn test_base24() {
|
||||
let input = "JTW3TJ7PFJ7V9CCMX84V9PFT8";
|
||||
let unbase24 = super::base24_decode(input);
|
||||
let unbase24 = super::base24_decode(input).unwrap();
|
||||
println!("{:?}", unbase24);
|
||||
let base24 = super::base24_encode(&unbase24);
|
||||
let base24 = super::base24_encode(&unbase24).unwrap();
|
||||
println!("{}", base24);
|
||||
assert_eq!(input, base24);
|
||||
}
|
||||
|
|
|
@ -2,6 +2,7 @@ pub mod bink1998;
|
|||
pub mod bink2002;
|
||||
pub mod confid;
|
||||
pub mod crypto;
|
||||
pub mod key;
|
||||
mod key;
|
||||
mod math;
|
||||
|
||||
pub const PK_LENGTH: usize = 25;
|
||||
const PK_LENGTH: usize = 25;
|
||||
|
|
11
src/math.rs
Normal file
11
src/math.rs
Normal 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
|
||||
}
|
Loading…
Add table
Reference in a new issue