Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(crypto): Optimize hexadecimal to byte conversion algorithm #311

Merged
merged 2 commits into from
Nov 18, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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(),
))
}