twetch_sdk/authentication/
mod.rs1use bsv_wasm::{hash::Hash, AESAlgorithms, PBKDF2Hashes, AES, KDF};
2use serde::*;
3use std::str;
4use wasm_bindgen::prelude::*;
5
6#[wasm_bindgen]
7
8pub struct Authentication {}
9
10#[wasm_bindgen]
11#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
12pub struct AuthenticationCipher {
13 email_hash: String,
14 cipher: String,
15 password_hash: String,
16 cipher_hash: Vec<u8>,
17}
18
19#[wasm_bindgen]
20impl AuthenticationCipher {
21 #[wasm_bindgen(js_name = getEmailHash)]
22 pub fn get_email_hash(&self) -> String {
23 self.email_hash.clone()
24 }
25
26 #[wasm_bindgen(js_name = getPasswordHash)]
27 pub fn get_password_hash(&self) -> String {
28 self.password_hash.clone()
29 }
30
31 #[wasm_bindgen(js_name = getCipher)]
32 pub fn get_cipher(&self) -> String {
33 self.cipher.clone()
34 }
35}
36
37#[wasm_bindgen]
38impl Authentication {
39 #[wasm_bindgen(js_name = getCipher)]
40 pub fn get_cipher(email: String, password: String) -> AuthenticationCipher {
41 let email_hash = Hash::sha_256(email.as_bytes()).to_hex();
42 let cipher = KDF::pbkdf2(
43 password.as_bytes().into(),
44 Some(email_hash.as_bytes().into()),
45 PBKDF2Hashes::SHA256,
46 10000,
47 32,
48 )
49 .get_hash();
50
51 let password_hash = Hash::sha_256(cipher.to_hex().as_bytes()).to_hex();
52
53 let response = AuthenticationCipher {
54 email_hash,
55 password_hash,
56 cipher: cipher.to_hex(),
57 cipher_hash: cipher.to_bytes(),
58 };
59
60 return response;
61 }
62}
63
64#[wasm_bindgen]
65impl AuthenticationCipher {
66 #[wasm_bindgen(js_name = decryptMnemonic)]
67 pub fn decrypt_mnemonic(&self, encrypted_mnemonic: String) -> Option<String> {
68 let iv = &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1];
69
70 let decrypted = match AES::decrypt(
71 &self.cipher_hash,
72 iv,
73 encrypted_mnemonic.as_bytes(),
74 AESAlgorithms::AES128_CTR,
75 ) {
76 Ok(v) => v,
77 Err(_) => return Some("error decrypting".to_string()),
78 };
79
80 let utf8 = match str::from_utf8(&decrypted) {
81 Ok(v) => v,
82 Err(_) => return Some("error utf8".to_string()),
83 };
84
85 return Some(utf8.into());
91 }
92}