Redesign lib public interface

This commit is contained in:
Alex Page 2023-06-23 16:57:12 -04:00
parent 83bfa98a38
commit 61d875757d
7 changed files with 603 additions and 562 deletions

View file

@ -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"))
}
}
}