Skip to content

Commit

Permalink
[Fix] fix rc4 crypto
Browse files Browse the repository at this point in the history
  • Loading branch information
canxin121 committed Jul 18, 2024
1 parent d596357 commit 2f7d940
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 29 deletions.
6 changes: 1 addition & 5 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,4 @@ serde_json = "1.0.119"
chrono = { version = "0.4.38", features = ["serde"] }
sha2 = "0.10.8"
base64 = "0.22.1"
rc4 = "0.1.0"
rc4 = { git = "https://github.com/rsdump/rc4" }
35 changes: 12 additions & 23 deletions rust/src/api/utils/crypto.rs
Original file line number Diff line number Diff line change
@@ -1,37 +1,24 @@
use anyhow::Result;
use base64::{engine::general_purpose::STANDARD, Engine as _};
use rc4::cipher::generic_array::typenum::U6;
use rc4::{Key, KeyInit, Rc4, StreamCipher};

pub async fn rc4_encrypt_to_base64(key: &str, input: &str) -> Result<String> {
let key_bytes = key.as_bytes();
let mut input_bytes = input.as_bytes().to_vec();

let rc4_key: &rc4::cipher::generic_array::GenericArray<u8, U6> = Key::from_slice(key_bytes);
let mut rc4 = Rc4::new(&rc4_key);

rc4.apply_keystream(&mut input_bytes);

let encrypted_base64 = STANDARD.encode(&input_bytes);

let input_bytes = input.as_bytes().to_vec();
let mut rc4 = rc4::Cipher::new(key_bytes)?;
let mut output_bytes: Vec<u8> = std::iter::repeat(0).take(input_bytes.len()).collect();
rc4.xor(&input_bytes, &mut output_bytes);
let encrypted_base64 = STANDARD.encode(&output_bytes);
Ok(encrypted_base64)
}

pub async fn rc4_decrypt_from_base64(key: &str, input: &str) -> Result<String> {
let mut input_bytes = STANDARD
let input_bytes = STANDARD
.decode(input)
.map_err(|e| anyhow::anyhow!("Base64 decode error: {:?}", e))?;

let key_bytes = key.as_bytes();

let rc4_key: &rc4::cipher::generic_array::GenericArray<u8, U6> = Key::from_slice(key_bytes);
let mut rc4 = Rc4::new(&rc4_key);

rc4.apply_keystream(&mut input_bytes);

let decrypted_string = String::from_utf8(input_bytes)
let mut rc4 = rc4::Cipher::new(key.as_bytes())?;
let mut output_bytes: Vec<u8> = std::iter::repeat(0).take(input_bytes.len()).collect();
rc4.xor(&input_bytes, &mut output_bytes);
let decrypted_string = String::from_utf8(output_bytes)
.map_err(|e| anyhow::anyhow!("UTF-8 conversion error: {:?}", e))?;

Ok(decrypted_string)
}

Expand All @@ -40,6 +27,8 @@ async fn test() {
let key = "Secret";
let input = "Attack at dawn";
let encrypted = rc4_encrypt_to_base64(key, input).await.unwrap();
println!("{}", encrypted);
let decrypted = rc4_decrypt_from_base64(key, &encrypted).await.unwrap();
println!("{}", decrypted);
assert_eq!(input, decrypted);
}

0 comments on commit 2f7d940

Please sign in to comment.