use base64::engine::general_purpose::STANDARD as B64_ENGINE;
use base64::Engine;
use flate2::read::ZlibDecoder;
use flate2::write::ZlibEncoder;
use flate2::Compression;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{Read, Write};
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PythonObfuscatorResult {
pub error: i64,
#[serde(default)]
pub output: Option<String>,
#[serde(default)]
pub demo: Option<bool>,
#[serde(default, rename = "license_expiration")]
pub license_expiration: Option<String>,
#[serde(default, rename = "usages_total")]
pub usages_total: Option<i64>,
#[serde(default, rename = "string_limit")]
pub string_limit: Option<i64>,
}
#[derive(Debug, Clone)]
pub enum PythonObfuscatorResponse {
Object(PythonObfuscatorResult),
Json(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CodeVirtualization {
#[serde(rename = "vm")]
Vm,
#[serde(rename = "fsa")]
Fsa,
#[serde(rename = "flat")]
Flat,
}
impl CodeVirtualization {
pub fn as_str(self) -> &'static str {
match self {
Self::Vm => "vm",
Self::Fsa => "fsa",
Self::Flat => "flat",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RenameStyle {
#[serde(rename = "il")]
Il,
#[serde(rename = "o0")]
O0,
#[serde(rename = "confusable")]
Confusable,
#[serde(rename = "hex")]
Hex,
#[serde(rename = "homoglyph")]
Homoglyph,
#[serde(rename = "mangled")]
Mangled,
}
impl RenameStyle {
pub fn as_str(self) -> &'static str {
match self {
Self::Il => "il",
Self::O0 => "o0",
Self::Confusable => "confusable",
Self::Hex => "hex",
Self::Homoglyph => "homoglyph",
Self::Mangled => "mangled",
}
}
}
#[derive(Debug, Clone)]
pub struct PythonObfuscator {
api_key: Option<String>,
client: reqwest::Client,
pub enable_compression: bool,
pub seed: Option<i64>,
pub randomization_density: Option<i64>,
pub rename_style: Option<RenameStyle>,
pub code_virtualization: Option<CodeVirtualization>,
pub self_defending: bool,
pub protection_linker: bool,
pub rename_variables: bool,
pub rename_parameters: bool,
pub rename_functions: bool,
pub rename_function_calls: bool,
pub shuffle_functions: bool,
pub resolve_constants: bool,
pub split_strings: bool,
pub modify_strings: bool,
pub encrypt_strings: bool,
pub string_char_array_vault: bool,
pub encrypt_integers: bool,
pub encrypt_floating: bool,
pub mba_binops: bool,
pub integers_to_floating: bool,
pub integers_to_arrays: bool,
pub floats_to_arrays: bool,
pub affine_integer_mask: bool,
pub array_int_crypt: bool,
pub array_char_crypt: bool,
pub array_double_crypt: bool,
pub array_string_crypt: bool,
pub insert_random_value_bucket: bool,
pub random_bucket_integers: bool,
pub random_bucket_arrays: bool,
pub random_bucket_functions: bool,
pub random_bucket_characters: bool,
pub random_bucket_anti_regex: bool,
pub random_bucket_autostart: bool,
pub insert_ternary_operators: bool,
pub complexify_booleans: bool,
pub opaque_branches: bool,
pub opaque_mixer_chain: bool,
pub insert_dead_code: bool,
pub try_finally_noise: bool,
pub decoy_functions: bool,
pub lambda_decoys: bool,
pub literal_padding: bool,
pub fake_import_markers: bool,
pub dynamic_getattr_calls: bool,
pub obfuscate_imports: bool,
pub callback_registration_stubs: bool,
pub detect_debugger: bool,
pub anti_vm: bool,
pub anti_sandbox: bool,
pub anti_emulator: bool,
pub remove_comments: bool,
}
impl PythonObfuscator {
pub const API_URL: &'static str = "https://www.pelock.com/api/python-obfuscator/v1";
pub const ERROR_SUCCESS: i64 = 0;
pub const ERROR_INPUT_SIZE: i64 = 1;
pub const ERROR_INPUT: i64 = 2;
pub const ERROR_PARSING: i64 = 3;
pub const ERROR_OBFUSCATION: i64 = 4;
pub const ERROR_OUTPUT: i64 = 5;
pub fn new(api_key: Option<String>) -> Self {
Self {
api_key,
client: reqwest::Client::new(),
enable_compression: false,
seed: None,
randomization_density: None,
rename_style: None,
code_virtualization: Some(CodeVirtualization::Vm),
self_defending: false,
protection_linker: false,
rename_variables: true,
rename_parameters: true,
rename_functions: true,
rename_function_calls: true,
shuffle_functions: true,
resolve_constants: true,
split_strings: true,
modify_strings: true,
encrypt_strings: true,
string_char_array_vault: true,
encrypt_integers: true,
encrypt_floating: true,
mba_binops: true,
integers_to_floating: true,
integers_to_arrays: true,
floats_to_arrays: true,
affine_integer_mask: true,
array_int_crypt: true,
array_char_crypt: true,
array_double_crypt: true,
array_string_crypt: true,
insert_random_value_bucket: true,
random_bucket_integers: true,
random_bucket_arrays: true,
random_bucket_functions: true,
random_bucket_characters: true,
random_bucket_anti_regex: true,
random_bucket_autostart: true,
insert_ternary_operators: true,
complexify_booleans: true,
opaque_branches: true,
opaque_mixer_chain: true,
insert_dead_code: true,
try_finally_noise: true,
decoy_functions: true,
lambda_decoys: true,
literal_padding: true,
fake_import_markers: true,
dynamic_getattr_calls: true,
obfuscate_imports: true,
callback_registration_stubs: true,
detect_debugger: false,
anti_vm: false,
anti_sandbox: false,
anti_emulator: false,
remove_comments: true,
}
}
pub async fn login(&self, return_as_object: bool) -> Option<PythonObfuscatorResponse> {
let mut params = HashMap::new();
params.insert("command".to_string(), "login".to_string());
self.post_request(params, return_as_object).await
}
pub async fn obfuscate_script_file(
&self,
script_file_path: &std::path::Path,
return_as_object: bool,
) -> Option<PythonObfuscatorResponse> {
let source = tokio::fs::read_to_string(script_file_path).await.ok()?;
if source.is_empty() {
return None;
}
self.obfuscate_script_source(&source, return_as_object).await
}
pub async fn obfuscate_script_source(
&self,
script_source: &str,
return_as_object: bool,
) -> Option<PythonObfuscatorResponse> {
let mut params = HashMap::new();
params.insert("command".to_string(), "obfuscate".to_string());
params.insert("source".to_string(), script_source.to_string());
self.post_request(params, return_as_object).await
}
async fn post_request(
&self,
mut params: HashMap<String, String>,
return_as_object: bool,
) -> Option<PythonObfuscatorResponse> {
if let Some(ref key) = self.api_key {
if !key.is_empty() {
params.insert("key".to_string(), key.clone());
}
}
if let Some(seed) = self.seed {
params.insert("seed".to_string(), seed.to_string());
}
if let Some(density) = self.randomization_density {
params.insert("randomization_density".to_string(), density.to_string());
}
if let Some(style) = self.rename_style {
params.insert("rename_style".to_string(), style.as_str().to_string());
}
if let Some(mode) = self.code_virtualization {
params.insert("code_virtualization".to_string(), mode.as_str().to_string());
}
if self.self_defending {
params.insert("self_defending".to_string(), "1".to_string());
}
if self.protection_linker {
params.insert("protection_linker".to_string(), "1".to_string());
}
if self.rename_variables {
params.insert("rename_variables".to_string(), "1".to_string());
}
if self.rename_parameters {
params.insert("rename_parameters".to_string(), "1".to_string());
}
if self.rename_functions {
params.insert("rename_functions".to_string(), "1".to_string());
}
if self.rename_function_calls {
params.insert("rename_function_calls".to_string(), "1".to_string());
}
if self.shuffle_functions {
params.insert("shuffle_functions".to_string(), "1".to_string());
}
if self.resolve_constants {
params.insert("resolve_constants".to_string(), "1".to_string());
}
if self.split_strings {
params.insert("split_strings".to_string(), "1".to_string());
}
if self.modify_strings {
params.insert("modify_strings".to_string(), "1".to_string());
}
if self.encrypt_strings {
params.insert("encrypt_strings".to_string(), "1".to_string());
}
if self.string_char_array_vault {
params.insert("string_char_array_vault".to_string(), "1".to_string());
}
if self.encrypt_integers {
params.insert("encrypt_integers".to_string(), "1".to_string());
}
if self.encrypt_floating {
params.insert("encrypt_floating".to_string(), "1".to_string());
}
if self.mba_binops {
params.insert("mba_binops".to_string(), "1".to_string());
}
if self.integers_to_floating {
params.insert("integers_to_floating".to_string(), "1".to_string());
}
if self.integers_to_arrays {
params.insert("integers_to_arrays".to_string(), "1".to_string());
}
if self.floats_to_arrays {
params.insert("floats_to_arrays".to_string(), "1".to_string());
}
if self.affine_integer_mask {
params.insert("affine_integer_mask".to_string(), "1".to_string());
}
if self.array_int_crypt {
params.insert("array_int_crypt".to_string(), "1".to_string());
}
if self.array_char_crypt {
params.insert("array_char_crypt".to_string(), "1".to_string());
}
if self.array_double_crypt {
params.insert("array_double_crypt".to_string(), "1".to_string());
}
if self.array_string_crypt {
params.insert("array_string_crypt".to_string(), "1".to_string());
}
if self.insert_random_value_bucket {
params.insert("insert_random_value_bucket".to_string(), "1".to_string());
}
if self.random_bucket_integers {
params.insert("random_bucket_integers".to_string(), "1".to_string());
}
if self.random_bucket_arrays {
params.insert("random_bucket_arrays".to_string(), "1".to_string());
}
if self.random_bucket_functions {
params.insert("random_bucket_functions".to_string(), "1".to_string());
}
if self.random_bucket_characters {
params.insert("random_bucket_characters".to_string(), "1".to_string());
}
if self.random_bucket_anti_regex {
params.insert("random_bucket_anti_regex".to_string(), "1".to_string());
}
if self.random_bucket_autostart {
params.insert("random_bucket_autostart".to_string(), "1".to_string());
}
if self.insert_ternary_operators {
params.insert("insert_ternary_operators".to_string(), "1".to_string());
}
if self.complexify_booleans {
params.insert("complexify_booleans".to_string(), "1".to_string());
}
if self.opaque_branches {
params.insert("opaque_branches".to_string(), "1".to_string());
}
if self.opaque_mixer_chain {
params.insert("opaque_mixer_chain".to_string(), "1".to_string());
}
if self.insert_dead_code {
params.insert("insert_dead_code".to_string(), "1".to_string());
}
if self.try_finally_noise {
params.insert("try_finally_noise".to_string(), "1".to_string());
}
if self.decoy_functions {
params.insert("decoy_functions".to_string(), "1".to_string());
}
if self.lambda_decoys {
params.insert("lambda_decoys".to_string(), "1".to_string());
}
if self.literal_padding {
params.insert("literal_padding".to_string(), "1".to_string());
}
if self.fake_import_markers {
params.insert("fake_import_markers".to_string(), "1".to_string());
}
if self.dynamic_getattr_calls {
params.insert("dynamic_getattr_calls".to_string(), "1".to_string());
}
if self.obfuscate_imports {
params.insert("obfuscate_imports".to_string(), "1".to_string());
}
if self.callback_registration_stubs {
params.insert("callback_registration_stubs".to_string(), "1".to_string());
}
if self.detect_debugger {
params.insert("detect_debugger".to_string(), "1".to_string());
}
if self.anti_vm {
params.insert("anti_vm".to_string(), "1".to_string());
}
if self.anti_sandbox {
params.insert("anti_sandbox".to_string(), "1".to_string());
}
if self.anti_emulator {
params.insert("anti_emulator".to_string(), "1".to_string());
}
if self.remove_comments {
params.insert("remove_comments".to_string(), "1".to_string());
}
if self.enable_compression {
if let Some(source) = params.get("source").cloned() {
let mut enc = ZlibEncoder::new(Vec::new(), Compression::best());
enc.write_all(source.as_bytes()).ok()?;
let compressed = enc.finish().ok()?;
params.insert("source".to_string(), B64_ENGINE.encode(compressed));
params.insert("compression".to_string(), "1".to_string());
}
}
let mut form = reqwest::multipart::Form::new();
for (k, v) in params {
form = form.text(k, v);
}
let response_text = self
.client
.post(Self::API_URL)
.header("User-Agent", "PELock Python Obfuscator")
.multipart(form)
.send()
.await
.ok()?
.text()
.await
.ok()?;
if response_text.is_empty() {
return None;
}
let mut result: PythonObfuscatorResult =
serde_json::from_str(&response_text).ok()?;
let mut depacked = false;
if self.enable_compression
&& result.error == Self::ERROR_SUCCESS
&& result.output.as_ref().is_some_and(|s| !s.is_empty())
{
let b64 = result.output.as_ref()?;
let buf = B64_ENGINE.decode(b64.as_bytes()).ok()?;
let mut decoder = ZlibDecoder::new(&buf[..]);
let mut out = String::new();
decoder.read_to_string(&mut out).ok()?;
result.output = Some(out);
depacked = true;
}
if return_as_object {
return Some(PythonObfuscatorResponse::Object(result));
}
if depacked {
let s = serde_json::to_string(&result).ok()?;
return Some(PythonObfuscatorResponse::Json(s));
}
Some(PythonObfuscatorResponse::Json(response_text))
}
}