Skip to content

Commit

Permalink
Merge pull request #311 from gngpp/feat
Browse files Browse the repository at this point in the history
feat(crypto): Optimize hexadecimal to byte conversion algorithm
  • Loading branch information
0x676e67 authored Nov 18, 2023
2 parents 2606db6 + 60efb57 commit 309aa6e
Showing 1 changed file with 17 additions and 18 deletions.
35 changes: 17 additions & 18 deletions openai/src/arkose/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ struct EncryptionData {
s: String,
}

#[inline]
pub fn encrypt(data: &str, key: &str) -> anyhow::Result<String> {
let enc_data = aes_encrypt(data, key)?;
Ok(serde_json::to_string(&enc_data)?)
}

#[inline]
pub fn decrypt(data: Vec<u8>, key: &str) -> anyhow::Result<String> {
let dec_data = ase_decrypt(data, key)?;
let data = String::from_utf8(dec_data)?;
Expand Down Expand Up @@ -74,7 +76,7 @@ fn ase_decrypt(content: Vec<u8>, password: &str) -> anyhow::Result<Vec<u8>> {

let ((key, _), iv) = (
default_evp_kdf(password.as_bytes(), &salt?).map_err(|s| anyhow::anyhow!(s))?,
hex_string_to_bytes(&encode_data.iv).ok_or(anyhow!("hex decode error"))?,
hex_to_bytes(&encode_data.iv).ok_or(anyhow!("hex decode error"))?,
);

use aes::cipher::{block_padding::Pkcs7, BlockDecryptMut, KeyIvInit};
Expand Down Expand Up @@ -128,39 +130,36 @@ fn evp_kdf(
Ok(derived_key_bytes[..key_size * 4].to_vec())
}

fn hex_string_to_bytes(hex_string: &str) -> Option<Vec<u8>> {
fn default_evp_kdf(password: &[u8], salt: &[u8]) -> Result<(Vec<u8>, Vec<u8>), &'static str> {
let key_size = 256 / 32;
let iv_size = 128 / 32;
let derived_key_bytes = evp_kdf(password, salt, key_size + iv_size, 1, "md5")?;
Ok((
derived_key_bytes[..key_size * 4].to_vec(),
derived_key_bytes[key_size * 4..].to_vec(),
))
}

fn hex_to_bytes(hex_string: &str) -> Option<Vec<u8>> {
let mut bytes = Vec::new();
let mut buffer = 0;
let mut buffer_length = 0;

for hex_char in hex_string.chars() {
for (i, hex_char) in hex_string.chars().enumerate() {
if let Some(digit) = hex_char.to_digit(16) {
buffer = (buffer << 4) | digit;
buffer_length += 1;

if buffer_length == 2 {
if i % 2 == 1 {
bytes.push(buffer as u8);
buffer = 0;
buffer_length = 0;
}
} else {
return None;
}
}

if buffer_length > 0 {
if hex_string.len() % 2 != 0 {
return None;
}

Some(bytes)
}

fn default_evp_kdf(password: &[u8], salt: &[u8]) -> Result<(Vec<u8>, Vec<u8>), &'static str> {
let key_size = 256 / 32;
let iv_size = 128 / 32;
let derived_key_bytes = evp_kdf(password, salt, key_size + iv_size, 1, "md5")?;
Ok((
derived_key_bytes[..key_size * 4].to_vec(),
derived_key_bytes[key_size * 4..].to_vec(),
))
}

0 comments on commit 309aa6e

Please sign in to comment.