use crate::error::{AnkerError, Result};
use aes::Aes128;
use cbc::cipher::block_padding::Pkcs7;
use cbc::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
use p256::ecdh::diffie_hellman;
use p256::{PublicKey, SecretKey};
type Aes128CbcEnc = cbc::Encryptor<Aes128>;
type Aes128CbcDec = cbc::Decryptor<Aes128>;
pub const PRIVATE_KEY_HEX: &str =
"7dfbea61cd95cee49c458ad7419e817f1ade9a66136de3c7d5787af1458e39f4";
pub fn checksum(bytes: &[u8]) -> u8 {
bytes.iter().fold(0u8, |acc, b| acc ^ b)
}
pub fn derive_shared_secret(device_pubkey_xy: &[u8]) -> Result<[u8; 32]> {
if device_pubkey_xy.len() != 64 {
return Err(AnkerError::Crypto(format!(
"expected 64-byte public key, got {}",
device_pubkey_xy.len()
)));
}
let priv_bytes =
hex::decode(PRIVATE_KEY_HEX).map_err(|e| AnkerError::Crypto(e.to_string()))?;
let secret =
SecretKey::from_slice(&priv_bytes).map_err(|e| AnkerError::Crypto(e.to_string()))?;
let mut sec1 = Vec::with_capacity(65);
sec1.push(0x04);
sec1.extend_from_slice(device_pubkey_xy);
let public = PublicKey::from_sec1_bytes(&sec1)
.map_err(|e| AnkerError::Crypto(format!("bad device point: {e}")))?;
let shared = diffie_hellman(secret.to_nonzero_scalar(), public.as_affine());
let raw = shared.raw_secret_bytes();
let mut out = [0u8; 32];
out.copy_from_slice(raw.as_slice());
Ok(out)
}
pub fn encrypt(secret: &[u8; 32], plaintext: &[u8]) -> Vec<u8> {
Aes128CbcEnc::new(secret[..16].into(), secret[16..].into())
.encrypt_padded_vec_mut::<Pkcs7>(plaintext)
}
pub fn decrypt(secret: &[u8; 32], ciphertext: &[u8]) -> Result<Vec<u8>> {
Aes128CbcDec::new(secret[..16].into(), secret[16..].into())
.decrypt_padded_vec_mut::<Pkcs7>(ciphertext)
.map_err(|e| AnkerError::Crypto(format!("decrypt/unpad failed: {e}")))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn checksum_is_xor() {
assert_eq!(checksum(&[0xff, 0x09, 0x00]), 0xf6);
assert_eq!(checksum(&[]), 0x00);
}
#[test]
fn aes_roundtrip() {
let secret = [7u8; 32];
let msg = b"a10121fe0503deadbeef";
let ct = encrypt(&secret, msg);
assert_eq!(ct.len() % 16, 0);
let pt = decrypt(&secret, &ct).unwrap();
assert_eq!(pt, msg);
}
#[test]
fn ecdh_rejects_bad_length() {
assert!(derive_shared_secret(&[0u8; 10]).is_err());
}
}