matrix_sdk_qrcode/utils.rs
1// Copyright 2021 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use qrcode::{bits::Bits, EcLevel, QrCode, Version};
16use ruma_common::serde::Base64;
17use vodozemac::Ed25519PublicKey;
18
19use crate::error::EncodingError;
20
21pub(crate) const HEADER: &[u8] = b"MATRIX";
22pub(crate) const VERSION: u8 = 0x2;
23pub(crate) const MAX_MODE: u8 = 0x2;
24pub(crate) const MIN_SECRET_LEN: usize = 8;
25
26pub(crate) fn to_bytes(
27 mode: u8,
28 flow_id: &str,
29 first_key: Ed25519PublicKey,
30 second_key: Ed25519PublicKey,
31 shared_secret: &Base64,
32) -> Result<Vec<u8>, EncodingError> {
33 let flow_id_len: u16 = flow_id.len().try_into()?;
34 let flow_id_len = flow_id_len.to_be_bytes();
35
36 let data = [
37 HEADER,
38 &[VERSION],
39 &[mode],
40 flow_id_len.as_ref(),
41 flow_id.as_bytes(),
42 first_key.as_bytes(),
43 second_key.as_bytes(),
44 shared_secret.as_bytes(),
45 ]
46 .concat();
47
48 Ok(data)
49}
50
51pub(crate) fn to_qr_code(
52 mode: u8,
53 flow_id: &str,
54 first_key: Ed25519PublicKey,
55 second_key: Ed25519PublicKey,
56 shared_secret: &Base64,
57) -> Result<QrCode, EncodingError> {
58 let data = to_bytes(mode, flow_id, first_key, second_key, shared_secret)?;
59
60 // Mobile clients seem to have trouble decoding the QR code that gets
61 // generated by `QrCode::new()` it seems to add a couple of data segments
62 // with different data modes/types. The parsers seem to assume a single
63 // data type and since we start with an ASCII `MATRIX` header the rest of
64 // the data gets treated as a string as well.
65 //
66 // We make sure that there isn't an ECI bit set and we just push the bytes,
67 // this seems to help since the decoder doesn't assume an encoding and
68 // treats everything as raw bytes.
69 let mut bits = Bits::new(Version::Normal(7));
70 bits.push_byte_data(&data)?;
71 bits.push_terminator(EcLevel::L)?;
72
73 Ok(QrCode::with_bits(bits, EcLevel::L)?)
74}