anker_solix 0.2.0

Library and CLI for monitoring/controlling Anker SOLIX power stations over Bluetooth LE
Documentation
//! Cryptography for the SOLIX BLE session.
//!
//! Anker firmware negotiates an ECDH (secp256r1 / NIST P-256) shared secret
//! and then encrypts all telemetry and command payloads with AES-128-CBC.
//!
//! The client's private key is a *fixed*, well-known scalar (the same one the
//! app ships with). Only the power station's ephemeral public key varies per
//! session, so the resulting shared secret is unique to each connection.
//!
//! The 32-byte shared secret is split: the first 16 bytes are the AES key and
//! the last 16 bytes are the IV.

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>;

/// The fixed client private key (secp256r1 scalar, big-endian) used for the
/// ECDH exchange. Lifted from the Anker app; hardcoding it is fine because the
/// "security" here only guards a ~10 m Bluetooth link.
pub const PRIVATE_KEY_HEX: &str =
    "7dfbea61cd95cee49c458ad7419e817f1ade9a66136de3c7d5787af1458e39f4";

/// XOR checksum over all bytes (used as the trailing packet byte).
pub fn checksum(bytes: &[u8]) -> u8 {
    bytes.iter().fold(0u8, |acc, b| acc ^ b)
}

/// Derive the 32-byte ECDH shared secret from the device's public key.
///
/// `device_pubkey_xy` is the raw 64-byte X||Y point as sent by the device in
/// negotiation stage 5 (parameter `a1`), *without* the `0x04` prefix.
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()))?;

    // Reassemble the uncompressed SEC1 point: 0x04 || X || Y.
    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)
}

/// AES-128-CBC encrypt with PKCS7 padding. Key = `secret[..16]`, IV = `secret[16..]`.
pub fn encrypt(secret: &[u8; 32], plaintext: &[u8]) -> Vec<u8> {
    Aes128CbcEnc::new(secret[..16].into(), secret[16..].into())
        .encrypt_padded_vec_mut::<Pkcs7>(plaintext)
}

/// AES-128-CBC decrypt with PKCS7 unpadding.
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());
    }
}