or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdconfiguration.mdindex.mdlicensing.mdobfuscation.mdplatform-support.mdproject-management.md

obfuscation.mddocs/

0

# Script Obfuscation

1

2

PyArmor's core obfuscation engine provides comprehensive Python script protection through multiple techniques including code transformation, string encryption, control flow obfuscation, and advanced binary compilation. The obfuscation system maintains script compatibility while providing strong protection against reverse engineering.

3

4

## Capabilities

5

6

### Core Obfuscation Functions

7

8

#### Script Encryption

9

10

Transform Python source code into obfuscated form with runtime decryption and validation.

11

12

```python { .api }

13

def encrypt_script(pubkey, filename: str, destname: str, wrap_mode: int = 1, obf_code: int = 1, obf_mod: int = 1, adv_mode: int = 0, rest_mode: int = 1, entry: int = 0, protection: int = 0, platforms = None, plugins = None, rpath = None, suffix: str = '', sppmode: bool = False, mixins = None) -> None:

14

"""

15

Obfuscate a single Python script file.

16

17

Args:

18

pubkey: Protection key from capsule

19

filename (str): Source script file path

20

destname (str): Destination obfuscated file path

21

wrap_mode (int): 0=disable, 1=enable wrap mode (default: 1)

22

obf_code (int): 0=none, 1=basic, 2=advanced code obfuscation (default: 1)

23

obf_mod (int): 0=disable, 1=enable module obfuscation (default: 1)

24

adv_mode (int): Advanced protection level 0-5 (default: 0)

25

rest_mode (int): Restriction mode 0-3 (default: 1)

26

entry (int): Entry point mode 0=normal, 1=entry (default: 0)

27

protection (int): Protection features bitmask (default: 0)

28

platforms: Target platform list or string (default: None)

29

plugins: Plugin list to apply (default: None)

30

rpath: Runtime path specification (default: None)

31

suffix (str): File suffix for runtime files (default: '')

32

sppmode (bool): Super plus mode enable (default: False)

33

mixins: Platform-specific mixins (default: None)

34

35

Raises:

36

EncryptError: If obfuscation fails

37

FileNotFoundError: If source file doesn't exist

38

PermissionError: If unable to write destination

39

"""

40

41

def pytransform_bootstrap(capsule = None, force: bool = False) -> None:

42

"""

43

Initialize PyArmor runtime environment and load protection library.

44

45

Args:

46

capsule: Protection capsule path (default: None for auto-detection)

47

force (bool): Force reinitialization even if already loaded (default: False)

48

49

Note:

50

This function must be called before any other PyArmor operations.

51

It initializes the core protection library (_pytransform) and sets up

52

the runtime environment for obfuscation operations.

53

"""

54

55

def make_capsule(filename: str = None) -> str:

56

"""

57

Generate protection capsule containing encryption keys.

58

59

Args:

60

filename (str, optional): Capsule file path, uses default if None

61

62

Returns:

63

str: Path to generated capsule file

64

65

Raises:

66

CapsuleError: If capsule generation fails

67

"""

68

69

def make_runtime(capsule, output: str, **kwargs) -> None:

70

"""

71

Generate runtime package for obfuscated scripts.

72

73

Args:

74

capsule: Protection capsule path or object

75

output (str): Output directory for runtime files

76

**kwargs: Runtime options

77

- platform (str): Target platform(s)

78

- package (int): 0=separate, 1=package with scripts

79

- suffix (str): Runtime file suffix

80

- bootstrap (int): Bootstrap code generation

81

- advanced (int): Advanced runtime features

82

83

Raises:

84

RuntimeError: If runtime generation fails

85

"""

86

87

def make_entry(entry: str, src: str, output: str, **kwargs) -> None:

88

"""

89

Generate entry point script with runtime initialization.

90

91

Args:

92

entry (str): Entry script name

93

src (str): Source directory

94

output (str): Output directory

95

**kwargs: Entry options

96

- bootstrap_code (int): Bootstrap generation mode

97

- suffix (str): File suffix for entry script

98

"""

99

100

def make_bootstrap_script(output: str, **kwargs) -> None:

101

"""

102

Generate standalone bootstrap script for runtime initialization.

103

104

Args:

105

output (str): Output directory

106

**kwargs: Bootstrap options

107

- capsule: Protection capsule

108

- template (str): Bootstrap template

109

"""

110

111

def make_project_command(platform: str, python: str, pyarmor: str, output: str) -> None:

112

"""

113

Generate platform-specific command script for project execution.

114

115

Args:

116

platform (str): Target platform specification

117

python (str): Python interpreter path

118

pyarmor (str): PyArmor script path

119

output (str): Output directory for generated script

120

"""

121

122

def search_plugins(plugins: list) -> list:

123

"""

124

Search and validate plugin files for obfuscation process.

125

126

Args:

127

plugins (list): List of plugin names or paths to search

128

129

Returns:

130

list: List of valid plugin file paths

131

132

Raises:

133

PluginError: If plugin files are not found or invalid

134

"""

135

136

def get_bind_key(filename: str) -> str:

137

"""

138

Extract hardware binding key from license or data file.

139

140

Args:

141

filename (str): Path to file containing binding information

142

143

Returns:

144

str: Hardware binding key extracted from file

145

146

Raises:

147

RuntimeError: If bind file not found or invalid

148

FileNotFoundError: If specified file doesn't exist

149

"""

150

```

151

152

### Advanced Obfuscation Engine (v8+)

153

154

Modern obfuscation system with enhanced protection and performance optimization.

155

156

```python { .api }

157

class Builder:

158

"""

159

Advanced obfuscation builder for v8+ interface.

160

"""

161

162

def __init__(self, ctx):

163

"""

164

Initialize builder with context.

165

166

Args:

167

ctx (Context): PyArmor context instance

168

"""

169

170

def generate_runtime_key(self, outer: bool = None) -> bytes:

171

"""

172

Generate runtime encryption key.

173

174

Args:

175

outer (bool, optional): Generate outer key for external runtime

176

177

Returns:

178

bytes: Generated runtime key data

179

"""

180

181

def generate_runtime_package(self, output: str) -> None:

182

"""

183

Generate complete runtime package with libraries.

184

185

Args:

186

output (str): Output directory path

187

"""

188

189

def process(self, options: dict, packer=None) -> None:

190

"""

191

Process obfuscation with comprehensive options.

192

193

Args:

194

options (dict): Obfuscation configuration

195

packer (optional): Packaging tool integration

196

"""

197

198

class Finder:

199

"""

200

Resource discovery and dependency management.

201

"""

202

203

def prepare(self, input_paths: list) -> None:

204

"""

205

Prepare resources for obfuscation processing.

206

207

Args:

208

input_paths (list): List of input file/directory paths

209

"""

210

211

def process(self) -> None:

212

"""

213

Discover and analyze all resources and dependencies.

214

"""

215

216

def append(self, resources: list) -> None:

217

"""

218

Add additional resources to processing queue.

219

220

Args:

221

resources (list): Additional resource objects

222

"""

223

```

224

225

### Obfuscation Modes and Levels

226

227

#### Basic Obfuscation Modes

228

229

```python { .api }

230

# Obfuscation mode constants

231

OBF_MODULE_MODE = {

232

0: "None", # No module obfuscation

233

1: "Simple" # Basic module protection

234

}

235

236

OBF_CODE_MODE = {

237

0: "None", # No code obfuscation

238

1: "Simple", # Basic code protection

239

2: "Fast" # Advanced code protection

240

}

241

242

WRAP_MODE = {

243

0: "None", # No wrapping

244

1: "Simple" # Function wrapping

245

}

246

247

ADVANCED_MODE = {

248

0: "Default", # Standard protection

249

1: "High", # Enhanced protection

250

2: "Super", # Super mode with C compilation

251

3: "VM Super", # Virtual machine + super mode

252

4: "Super Plus", # Maximum protection

253

5: "Super Pro" # Professional grade protection

254

}

255

256

RESTRICT_MODE = {

257

0: "None", # No restrictions

258

1: "Import", # Import restrictions

259

2: "Private", # Private mode

260

3: "Restrict" # Full restriction mode

261

}

262

```

263

264

#### Advanced Protection Features

265

266

```python { .api }

267

def enable_bcc_mode(options: dict) -> dict:

268

"""

269

Enable Binary Code Coverage protection.

270

271

Args:

272

options (dict): Current obfuscation options

273

274

Returns:

275

dict: Updated options with BCC enabled

276

277

Note:

278

BCC mode compiles Python functions to machine code

279

for maximum protection. Platform specific.

280

"""

281

282

def enable_jit_mode(options: dict) -> dict:

283

"""

284

Enable Just-In-Time compilation protection.

285

286

Args:

287

options (dict): Current obfuscation options

288

289

Returns:

290

dict: Updated options with JIT enabled

291

"""

292

293

def enable_rft_mode(options: dict) -> dict:

294

"""

295

Enable Runtime Function Transformation.

296

297

Args:

298

options (dict): Current obfuscation options

299

300

Returns:

301

dict: Updated options with RFT enabled

302

"""

303

304

def enable_themida_protection(options: dict) -> dict:

305

"""

306

Enable Themida anti-debugging protection (Windows only).

307

308

Args:

309

options (dict): Current obfuscation options

310

311

Returns:

312

dict: Updated options with Themida enabled

313

314

Note:

315

Requires Windows platform and Themida license

316

"""

317

```

318

319

### String and Constant Protection

320

321

```python { .api }

322

def enable_string_mixing(options: dict) -> dict:

323

"""

324

Enable string constant encryption and mixing.

325

326

Args:

327

options (dict): Obfuscation options

328

329

Returns:

330

dict: Options with string mixing enabled

331

332

Note:

333

Encrypts string literals and mixes them with dummy data

334

"""

335

336

def protect_constants(script_path: str, **kwargs) -> None:

337

"""

338

Apply constant protection to numeric and string literals.

339

340

Args:

341

script_path (str): Path to script file

342

**kwargs: Protection options

343

- level (int): Protection intensity 1-3

344

- strings (bool): Protect string constants

345

- numbers (bool): Protect numeric constants

346

"""

347

```

348

349

### Cross-Platform Obfuscation

350

351

```python { .api }

352

def generate_cross_platform(scripts: list, platforms: list, **kwargs) -> None:

353

"""

354

Generate obfuscated scripts for multiple target platforms.

355

356

Args:

357

scripts (list): List of script file paths

358

platforms (list): Target platform specifications

359

**kwargs: Cross-platform options

360

- output (str): Output directory

361

- shared_runtime (bool): Use shared runtime package

362

363

Example platforms:

364

['linux.x86_64', 'windows.x86_64', 'darwin.x86_64']

365

"""

366

367

def download_platform_library(platform: str, **kwargs) -> str:

368

"""

369

Download platform-specific runtime library.

370

371

Args:

372

platform (str): Platform specification (e.g., 'linux.x86_64')

373

**kwargs: Download options

374

- update (bool): Force update existing library

375

- timeout (int): Download timeout in seconds

376

377

Returns:

378

str: Path to downloaded library

379

380

Raises:

381

DownloadError: If download fails

382

PlatformError: If platform not supported

383

"""

384

```

385

386

## Usage Examples

387

388

### Basic Script Obfuscation

389

390

```python

391

from pyarmor import utils

392

393

# Initialize PyArmor

394

utils.pytransform_bootstrap()

395

396

# Generate capsule and runtime

397

capsule = utils.make_capsule()

398

utils.make_runtime(capsule, "dist")

399

400

# Obfuscate single script

401

utils.encrypt_script(capsule, "hello.py", "dist/hello.py")

402

403

# Create entry point

404

utils.make_entry("hello.py", ".", "dist")

405

```

406

407

### Advanced Obfuscation Configuration

408

409

```python

410

# Configure advanced obfuscation

411

options = {

412

'obf_code': 2, # Advanced code obfuscation

413

'obf_mod': 1, # Module obfuscation

414

'wrap_mode': 1, # Function wrapping

415

'advanced': 2, # Super mode

416

'restrict': 2, # Private mode

417

'cross_protection': 1, # Cross protection

418

'bootstrap_code': 1 # Bootstrap generation

419

}

420

421

# Apply to script

422

utils.encrypt_script(capsule, "main.py", "dist/main.py", **options)

423

```

424

425

### Modern Builder Usage

426

427

```python

428

from pyarmor.cli.generate import Builder

429

from pyarmor.cli.context import Context

430

431

# Initialize context and builder

432

ctx = Context()

433

builder = Builder(ctx)

434

435

# Configure obfuscation options

436

options = {

437

'inputs': ['src/'],

438

'output': 'dist',

439

'recursive': True,

440

'obf_code': 2,

441

'mix_str': True,

442

'enable_bcc': True,

443

'restrict_module': 2,

444

'platforms': ['linux.x86_64', 'windows.x86_64']

445

}

446

447

# Process obfuscation

448

builder.process(options)

449

```

450

451

### String Protection Example

452

453

```python

454

# Enable comprehensive string protection

455

options = {

456

'mix_str': True, # String mixing

457

'advanced': 3, # VM mode for strings

458

'assert_call': True, # Function call validation

459

'assert_import': True # Import validation

460

}

461

462

utils.encrypt_script(capsule, "sensitive.py", "dist/sensitive.py", **options)

463

```

464

465

### Cross-Platform Deployment

466

467

```python

468

# Multi-platform obfuscation

469

platforms = [

470

'linux.x86_64', # Linux 64-bit

471

'windows.x86_64', # Windows 64-bit

472

'darwin.x86_64', # macOS Intel

473

'darwin.arm64', # macOS Apple Silicon

474

'linux.aarch64' # Linux ARM64

475

]

476

477

# Download required libraries

478

for platform in platforms:

479

utils.download_pytransform(platform)

480

481

# Generate cross-platform runtime

482

utils.make_runtime(capsule, "dist", platform=",".join(platforms))

483

484

# Obfuscate with platform support

485

utils.encrypt_script(capsule, "app.py", "dist/app.py",

486

platform=",".join(platforms))

487

```

488

489

## Error Handling

490

491

```python

492

from pyarmor.utils import EncryptError, RuntimeError, CapsuleError

493

494

try:

495

# Obfuscation operations

496

capsule = utils.make_capsule()

497

utils.make_runtime(capsule, "dist")

498

utils.encrypt_script(capsule, "main.py", "dist/main.py")

499

500

except CapsuleError as e:

501

print(f"Capsule generation failed: {e}")

502

503

except RuntimeError as e:

504

print(f"Runtime generation failed: {e}")

505

506

except EncryptError as e:

507

print(f"Script obfuscation failed: {e}")

508

509

except FileNotFoundError:

510

print("Source file not found")

511

512

except PermissionError:

513

print("Permission denied - check file/directory permissions")

514

```

515

516

## Performance Considerations

517

518

- **Super Mode**: Provides maximum protection but increases startup time

519

- **String Mixing**: Adds runtime overhead for string operations

520

- **BCC Mode**: Optimal performance with binary compilation

521

- **Cross Protection**: Minimal overhead with strong anti-tampering

522

- **VM Mode**: Higher protection with moderate performance impact