tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

storage.rs (1389B)


      1 /* This Source Code Form is subject to the terms of the Mozilla Public
      2 * License, v. 2.0. If a copy of the MPL was not distributed with this
      3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
      4 
      5 use nsstring::nsACString;
      6 use std::fs;
      7 use std::io;
      8 
      9 pub fn get_storage_path(storage_prefix: &nsACString) -> String {
     10    format!("{storage_prefix}.sqlite.enc")
     11 }
     12 
     13 pub fn get_key_path(storage_prefix: &nsACString) -> String {
     14    format!("{storage_prefix}.key")
     15 }
     16 
     17 fn read_existing_storage_key(key_path: &str) -> io::Result<[u8; 32]> {
     18    let key_hex = fs::read_to_string(key_path)?;
     19    let bytes = hex::decode(&key_hex).map_err(|e| io::Error::other(e))?;
     20    bytes[..].try_into().map_err(|e| io::Error::other(e))
     21 }
     22 
     23 pub fn get_storage_key(storage_prefix: &nsACString) -> io::Result<[u8; 32]> {
     24    // Get the key path
     25    let key_path = get_key_path(storage_prefix);
     26 
     27    // Try to read the existing key
     28    if let Ok(key) = read_existing_storage_key(&key_path) {
     29        return Ok(key);
     30    }
     31 
     32    // We failed to read the key, so it must either not exist, or is invalid.
     33    // Generate a new one.
     34    nss_gk_api::init();
     35    let key: [u8; 32] = nss_gk_api::p11::random(32)[..]
     36        .try_into()
     37        .expect("nss returned the wrong number of bytes");
     38 
     39    // Write the key to the file
     40    std::fs::write(key_path, &hex::encode(&key))?;
     41 
     42    // Return the key
     43    Ok(key)
     44 }