-
Notifications
You must be signed in to change notification settings - Fork 37
Add cove-keyteleport crate: Key Teleport crypto primitives (mnemonic/xprv) #676
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
6da0fbd
5a323ef
526555a
4659896
e6f1fcf
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| 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 } | ||
| 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
|
|
||
| # encoding | ||
| data-encoding = { workspace = true } | ||
| bbqr = { workspace = true } | ||
|
|
||
| # error handling | ||
| thiserror = { workspace = true } | ||
|
|
||
| [dev-dependencies] | ||
| hex = { workspace = true } | ||
| 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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()); | ||
| } | ||
| } | ||
| 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)); | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Remove unused
hmacdirect dependency.Per
rust/crates/cove-keyteleport/src/crypto.rs, onlypbkdf2::pbkdf2_hmacandsha2are used directly;hmacappears solely as a transitive dependency ofpbkdf2. 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
🤖 Prompt for AI Agents