Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ cove-device = { path = "./crates/cove-device" }
cove-bdk = { path = "./crates/cove-bdk" }
cove-tokio = { path = "./crates/cove-tokio" }
cove-http = { path = "./crates/cove-http" }
cove-keyteleport = { path = "./crates/cove-keyteleport" }

# bitcoin
bitcoin = { workspace = true }
Expand Down
32 changes: 32 additions & 0 deletions rust/crates/cove-keyteleport/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
[package]
name = "cove-keyteleport"
version = "0.1.0"
edition = "2024"

[dependencies]
# bitcoin / secp256k1
bitcoin = { workspace = true }
bip39 = { workspace = true }

# crypto primitives
sha2 = { workspace = true }
hmac = { workspace = true }
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Remove unused hmac direct dependency.

Per rust/crates/cove-keyteleport/src/crypto.rs, only pbkdf2::pbkdf2_hmac and sha2 are used directly; hmac appears solely as a transitive dependency of pbkdf2. Declaring it as a direct dep here adds noise and risks version drift from the transitive one.

Proposed fix
 # crypto primitives
 sha2 = { workspace = true }
-hmac = { workspace = true }
 rand = { workspace = true }
 zeroize = { workspace = true, features = ["derive"] }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
hmac = { workspace = true }
# crypto primitives
sha2 = { workspace = true }
rand = { workspace = true }
zeroize = { workspace = true, features = ["derive"] }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@rust/crates/cove-keyteleport/Cargo.toml` at line 13, Remove the direct hmac
dependency from Cargo.toml because crypto.rs only uses pbkdf2::pbkdf2_hmac and
types from sha2, and hmac is provided transitively by pbkdf2; update Cargo.toml
by deleting the line "hmac = { workspace = true }" so the crate relies on the
transitive hmac version, leaving pbkdf2 and sha2 entries intact and ensuring no
code changes in functions like pbkdf2::pbkdf2_hmac in src/crypto.rs are
necessary.

rand = { workspace = true }
zeroize = { workspace = true, features = ["derive"] }

# AES-256-CTR
aes = "0.8"
ctr = "0.9"

# PBKDF2-SHA512
pbkdf2 = "0.12"
Comment on lines +18 to +22
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Crypto crate versions not pinned in workspace

aes = "0.8", ctr = "0.9", and pbkdf2 = "0.12" are declared with inline version specifiers instead of via the workspace. All other crates in this workspace use workspace = true for version management. This inconsistency means these versions won't be bumped uniformly when the workspace is updated and can drift from what other crates' transitive dependencies resolve to. Consider adding them to the root Cargo.toml [workspace.dependencies] section and referencing them as workspace = true here.


# encoding
data-encoding = { workspace = true }
bbqr = { workspace = true }

# error handling
thiserror = { workspace = true }

[dev-dependencies]
hex = { workspace = true }
137 changes: 137 additions & 0 deletions rust/crates/cove-keyteleport/src/bbqr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
/// Minimal BBQr encoder/decoder for Key Teleport packet types (R and S).
///
/// BBQr format: `B$<encoding><file_type><num_parts_hex2><part_index_hex2><base32_data>`
/// For single-frame packets: num_parts=01, part_index=00.
/// Encoding byte `2` = Base32, no compression (as required by the COLDCARD spec).
use bbqr::encode::Encoding;
use data_encoding::BASE32_NOPAD;

use crate::error::Error;

/// Key Teleport BBQr file type codes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyTeleportFileType {
/// `R` — receiver packet (encrypted pubkey)
Receiver,
/// `S` — sender packet (sender pubkey + encrypted body)
Sender,
}

impl KeyTeleportFileType {
pub fn as_char(self) -> char {
match self {
KeyTeleportFileType::Receiver => 'R',
KeyTeleportFileType::Sender => 'S',
}
}

fn from_char(c: char) -> Result<Self, Error> {
match c {
'R' => Ok(KeyTeleportFileType::Receiver),
'S' => Ok(KeyTeleportFileType::Sender),
other => Err(Error::InvalidBbqr(format!("unknown Key Teleport type: '{other}'"))),
}
}
}

/// Encode binary data as a single-frame BBQr string with the given Key Teleport file type.
pub fn encode(data: &[u8], file_type: KeyTeleportFileType) -> String {
let b32 = BASE32_NOPAD.encode(data);
// num_parts=01 (1 frame total), part_index=00 (first/only frame)
// Encoding::Base32 corresponds to byte '2' per the BBQr spec
format!("B${}{}0100{}", Encoding::Base32.as_byte() as char, file_type.as_char(), b32)
}

/// Decode a single-frame BBQr string, returning the file type and binary payload.
/// Multi-frame packets are rejected — higher-level transport code handles reassembly.
pub fn decode(s: &str) -> Result<(KeyTeleportFileType, Vec<u8>), Error> {
let s = s.trim().to_uppercase();

let rest =
s.strip_prefix("B$").ok_or_else(|| Error::InvalidBbqr("missing 'B$' header".into()))?;

if rest.len() < 6 {
return Err(Error::InvalidBbqr("too short to be a valid BBQr packet".into()));
}

let mut chars = rest.chars();
let encoding_char = chars.next().unwrap();
let encoding = Encoding::from_byte(encoding_char as u8).ok_or_else(|| {
Error::InvalidBbqr(format!("unknown encoding '{encoding_char}'"))
})?;
if encoding != Encoding::Base32 {
return Err(Error::InvalidBbqr(format!(
"unsupported encoding '{encoding_char}' (only Base32/'2' is supported)"
)));
}

let file_type = KeyTeleportFileType::from_char(chars.next().unwrap())?;

// num_parts and part_index are 2 uppercase hex chars each
let header_tail: String = chars.take(4).collect();
if header_tail.len() != 4 {
return Err(Error::InvalidBbqr("truncated header".into()));
}
let num_parts = u8::from_str_radix(&header_tail[0..2], 16)
.map_err(|_| Error::InvalidBbqr("bad num_parts".into()))?;
let part_index = u8::from_str_radix(&header_tail[2..4], 16)
.map_err(|_| Error::InvalidBbqr("bad part_index".into()))?;

if num_parts != 1 || part_index != 0 {
return Err(Error::InvalidBbqr(format!(
"multi-frame BBQr not supported here (num_parts={num_parts}, part_index={part_index})"
)));
}

let b32_data = &s[8..]; // "B$" + encoding + type + 4 header chars = 8
let data = BASE32_NOPAD
.decode(b32_data.as_bytes())
.map_err(|e| Error::InvalidBbqr(format!("Base32 decode failed: {e}")))?;

Ok((file_type, data))
}
Comment on lines +37 to +92
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should use the bbqr here, we are already using it in the app

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pradhyum6144 you didnt address this


#[cfg(test)]
mod tests {
use super::*;

#[test]
fn encode_decode_roundtrip_receiver() {
let data = vec![0xAAu8; 33];
let encoded = encode(&data, KeyTeleportFileType::Receiver);
assert!(encoded.starts_with("B$2R0100"));
let (ft, decoded) = decode(&encoded).unwrap();
assert_eq!(ft, KeyTeleportFileType::Receiver);
assert_eq!(decoded, data);
}

#[test]
fn encode_decode_roundtrip_sender() {
let mut data = vec![0x01u8; 33];
data.extend_from_slice(&[0xBBu8; 80]);
let encoded = encode(&data, KeyTeleportFileType::Sender);
assert!(encoded.starts_with("B$2S0100"));
let (ft, decoded) = decode(&encoded).unwrap();
assert_eq!(ft, KeyTeleportFileType::Sender);
assert_eq!(decoded, data);
}

#[test]
fn decode_known_example() {
// From keyteleport.com: B$2R0100VHT2AGUUH7KUZUUSTOWOIWHJX3XM7GA2N4BHQOXDFHXLVHVA7K6ZO
let s = "B$2R0100VHT2AGUUH7KUZUUSTOWOIWHJX3XM7GA2N4BHQOXDFHXLVHVA7K6ZO";
let (ft, data) = decode(s).unwrap();
assert_eq!(ft, KeyTeleportFileType::Receiver);
assert_eq!(data.len(), 33);
}

#[test]
fn rejects_wrong_header() {
assert!(decode("QR2R0100AAAA").is_err());
}

#[test]
fn rejects_unknown_file_type() {
assert!(decode("B$2E0100AAAA").is_err());
}
}
121 changes: 121 additions & 0 deletions rust/crates/cove-keyteleport/src/crypto.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
use aes::Aes256;
use aes::cipher::{KeyIvInit as _, StreamCipher as _};
use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};
use ctr::Ctr128BE;
use pbkdf2::pbkdf2_hmac;
use sha2::{Digest as _, Sha256, Sha512};

/// Derive the shared session key using ECDH.
///
/// Per the Key Teleport spec: SHA256(X || Y) of the shared point where X and Y
/// are the full uncompressed coordinates (64 bytes total).
pub(crate) fn session_key(local_privkey: &SecretKey, remote_pubkey: &PublicKey) -> [u8; 32] {
let secp = Secp256k1::new();
let scalar = Scalar::from_be_bytes(local_privkey.secret_bytes())
.expect("secret key bytes are always a valid scalar");
let point = remote_pubkey.mul_tweak(&secp, &scalar).expect("valid EC multiplication");
// serialize_uncompressed: 04 || X(32) || Y(32) — drop the 04 prefix
let uncompressed = point.serialize_uncompressed();
Sha256::digest(&uncompressed[1..]).into()
}

/// AES-256-CTR encrypt or decrypt (same operation — XOR keystream).
/// Zero IV as specified by the Key Teleport protocol.
pub(crate) fn aes256ctr(key: &[u8; 32], data: &[u8]) -> Vec<u8> {
let iv = [0u8; 16];
let mut cipher = Ctr128BE::<Aes256>::new(key.into(), &iv.into());
let mut out = data.to_vec();
cipher.apply_keystream(&mut out);
out
}

/// Derive the AES key used to encrypt/decrypt the receiver's pubkey in the R packet.
/// Key = SHA256(zero-padded 8-digit decimal string of the numeric code).
pub(crate) fn receiver_pubkey_key(numeric_code: u32) -> [u8; 32] {
let code_str = format!("{:08}", numeric_code);
Sha256::digest(code_str.as_bytes()).into()
}

/// Stretch the teleport password using PBKDF2-SHA512.
/// Per spec: password = session_key, salt = teleport_pass, iter = 5000.
/// Returns the upper 256 bits (first 32 bytes) of the 512-bit output.
pub(crate) fn pbkdf2_stretch(session_key: &[u8; 32], teleport_pass: &[u8]) -> [u8; 32] {
let mut out = [0u8; 64];
pbkdf2_hmac::<Sha512>(session_key, teleport_pass, 5000, &mut out);
out[..32].try_into().expect("32 bytes from 64-byte output")
}

/// 2-byte checksum: last 2 bytes of SHA256(data).
pub(crate) fn checksum(data: &[u8]) -> [u8; 2] {
let hash = Sha256::digest(data);
[hash[30], hash[31]]
}

/// Verify the 2-byte checksum appended to `data_with_checksum`.
/// Returns the payload bytes (without checksum) if valid.
pub(crate) fn verify_checksum(data_with_checksum: &[u8]) -> Option<&[u8]> {
if data_with_checksum.len() < 2 {
return None;
}
let (body, cs) = data_with_checksum.split_at(data_with_checksum.len() - 2);
let expected = checksum(body);
if cs == expected { Some(body) } else { None }
}

#[cfg(test)]
mod tests {
use super::*;
use bitcoin::secp256k1::Secp256k1;

#[test]
fn session_key_is_symmetric() {
use rand::RngExt as _;
let secp = Secp256k1::new();
let mut bytes_a = [0u8; 32];
let mut bytes_b = [0u8; 32];
rand::rng().fill(&mut bytes_a);
rand::rng().fill(&mut bytes_b);
let sk_a = SecretKey::from_slice(&bytes_a).unwrap();
let sk_b = SecretKey::from_slice(&bytes_b).unwrap();
let pk_a = sk_a.public_key(&secp);
let pk_b = sk_b.public_key(&secp);

let ka = session_key(&sk_a, &pk_b);
let kb = session_key(&sk_b, &pk_a);
assert_eq!(ka, kb, "ECDH must be symmetric");
}

#[test]
fn aes256ctr_roundtrip() {
let key = [0x42u8; 32];
let plain = b"hello key teleport";
let cipher = aes256ctr(&key, plain);
let recovered = aes256ctr(&key, &cipher);
assert_eq!(recovered, plain);
}

#[test]
fn checksum_verify_roundtrip() {
let data = b"some payload data";
let cs = checksum(data);
let mut with_cs = data.to_vec();
with_cs.extend_from_slice(&cs);
assert_eq!(verify_checksum(&with_cs), Some(data.as_slice()));
}

#[test]
fn checksum_detects_corruption() {
let data = b"some payload data";
let cs = checksum(data);
let mut with_cs = data.to_vec();
with_cs.extend_from_slice(&cs);
with_cs[0] ^= 0xFF;
assert_eq!(verify_checksum(&with_cs), None);
}

#[test]
fn receiver_pubkey_key_is_deterministic() {
assert_eq!(receiver_pubkey_key(12345678), receiver_pubkey_key(12345678));
assert_ne!(receiver_pubkey_key(12345678), receiver_pubkey_key(99999999));
}
}
Loading