crypto add arbitrary purpose

This commit is contained in:
Sosthene00 2024-04-18 23:10:18 +02:00
parent 8f11111943
commit 9a34a02063

View File

@ -10,8 +10,8 @@ use sp_client::{
Txid,
},
silentpayments::{
sending::SilentPaymentAddress,
bitcoin_hashes::{sha256t_hash_newtype, HashEngine, Hash}
bitcoin_hashes::{sha256t_hash_newtype, Hash, HashEngine},
sending::SilentPaymentAddress,
},
};
@ -47,7 +47,7 @@ impl AnkSharedSecret {
Self(SharedSecret::from_bytes(t_hash.to_byte_array()))
}
pub fn to_byte_array(&self) -> [u8;SECRET_KEY_SIZE] {
pub fn to_byte_array(&self) -> [u8; SECRET_KEY_SIZE] {
self.0.secret_bytes()
}
@ -99,6 +99,7 @@ impl HalfKey {
pub enum Purpose {
Login,
ThirtyTwoBytes,
Arbitrary,
}
pub type CipherText = Vec<u8>;
@ -166,6 +167,10 @@ impl Aes256Decryption {
let thirty_two_buf = self.decrypt_thirty_two()?;
Ok(thirty_two_buf.to_vec())
}
Purpose::Arbitrary => {
let arbitrary = self.decrypt_arbitrary()?;
Ok(arbitrary)
}
}
}
@ -194,6 +199,14 @@ impl Aes256Decryption {
thirty_two.copy_from_slice(&plain);
Ok(thirty_two)
}
fn decrypt_arbitrary(&self) -> Result<Vec<u8>> {
let cipher = Aes256Gcm::new(&self.aes_key.into());
let plain = cipher
.decrypt(&self.nonce.into(), &*self.cipher_text)
.map_err(|e| Error::msg(format!("{}", e)))?;
Ok(plain)
}
}
pub struct Aes256Encryption {
@ -266,6 +279,7 @@ impl Aes256Encryption {
match self.purpose {
Purpose::Login => self.encrypt_login(),
Purpose::ThirtyTwoBytes => self.encrypt_thirty_two(),
Purpose::Arbitrary => self.encrypt_arbitrary(),
}
}
@ -296,6 +310,17 @@ impl Aes256Encryption {
res.extend_from_slice(&cipher_text);
Ok(res)
}
fn encrypt_arbitrary(&self) -> Result<CipherText> {
let cipher = Aes256Gcm::new(&self.aes_key.into());
let cipher_text = cipher
.encrypt(&self.nonce.into(), &*self.plaintext)
.map_err(|e| Error::msg(format!("{}", e)))?;
let mut res = Vec::with_capacity(self.nonce.len() + cipher_text.len());
res.extend_from_slice(&self.nonce);
res.extend_from_slice(&cipher_text);
Ok(res)
}
}
#[cfg(test)]