mirror of
https://github.com/Whitecat18/static_encrypt
synced 2026-06-06 15:04:27 +00:00
Version 0.1.0 Release
This commit is contained in:
+40
@@ -0,0 +1,40 @@
|
||||
[package]
|
||||
name = "static_encrypt"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
authors = ["5mukx <staffs@5mukx.site>"]
|
||||
description = "Compile-time / static string encryption for Rust"
|
||||
readme = "README.md"
|
||||
homepage = "https://github.com/Whitecat18/static_encrypt"
|
||||
repository = "https://github.com/Whitecat18/static_encrypt"
|
||||
license = "Apache-2.0"
|
||||
keywords = ["encryption", "obfuscation", "string", "static", "compile-time"]
|
||||
categories = ["cryptography", "no-std", "encoding"]
|
||||
exclude = [".github", "tests/data/*", "target/*", "Cargo.lock"]
|
||||
|
||||
[[test]]
|
||||
name = "test"
|
||||
path = "tests/test.rs"
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
lazy_static = "1.5.0"
|
||||
proc-macro2 = "1.0.105"
|
||||
quote = "1.0.43"
|
||||
rand = "0.9.2"
|
||||
|
||||
[dev-dependencies]
|
||||
trybuild = "1.0"
|
||||
|
||||
[build-dependencies]
|
||||
rand = "0.9"
|
||||
[features]
|
||||
default = ["xor"]
|
||||
xor = []
|
||||
rc4 = []
|
||||
xorshift = []
|
||||
vigenere = []
|
||||
lcg = []
|
||||
xorr = []
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Smukx ♠
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,132 @@
|
||||
# Static Encrypt
|
||||
|
||||
**Protect your strings from static analysis tools.**
|
||||
|
||||
`static_encrypt` is a Rust proc-macro crate that encrypts string literals at **compile time**. The plain text strings never appear in your compiled binary. They are encrypted using a **unique, random key generated during every build**, and only decrypted at runtime when needed.
|
||||
|
||||
This crate is a modernized and advanced version, featuring 6 different encryption algorithms and automatic key management.
|
||||
|
||||
## Features
|
||||
|
||||
* **Compile-Time Encryption:** Strings are encrypted before they ever reach the binary.
|
||||
* **Unique Random Keys:** A fresh random key is generated automatically via `build.rs` every time you compile. No need to manage environment variables manually.
|
||||
* **6 Encryption Algorithms:** Choose the balance of speed and obfuscation that fits your needs.
|
||||
* **Zero Dependencies (Runtime):** Extremely lightweight runtime footprint.
|
||||
* **UTF-8 Support:** Full support for Emoji, CJK (Chinese/Japanese/Korean), and Cyrillic characters.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
cargo add static_encrypt
|
||||
```
|
||||
|
||||
(or)
|
||||
|
||||
Add this to your `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
static_encrypt = "0.1.0"
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Example:
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate static_encrypt;
|
||||
|
||||
// Initialize the decryption runtime.
|
||||
// This injects the decryption code specific to your selected algorithm.
|
||||
set_crypt!();
|
||||
|
||||
fn main() {
|
||||
// Use enc!() to encrypt strings.
|
||||
let message = enc!("This is a secret message");
|
||||
|
||||
println!("Message: {}", message);
|
||||
}
|
||||
```
|
||||
|
||||
Real Example:
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate static_encrypt;
|
||||
|
||||
set_crypt!();
|
||||
|
||||
use reqwest::header::{AUTHORIZATION, HeaderValue};
|
||||
use reqwest::Client;
|
||||
use std::env;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
let enc_key =
|
||||
let api_key = std::env::var(enc!("TEST"))
|
||||
.expect("MY_API_KEY not set in environment variables");
|
||||
|
||||
let client = Client::new();
|
||||
let url = enc!("https://api.example.com/data");
|
||||
|
||||
let response = client.get(url)
|
||||
.header(AUTHORIZATION, format!("Bearer {}", api_key))
|
||||
.send()
|
||||
.await?
|
||||
.text()
|
||||
.await?;
|
||||
|
||||
println!("Response: {}", response);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### 2. Switching Algorithms
|
||||
|
||||
You can change the underlying encryption algorithm using **Cargo Features**. The default is `xor`.
|
||||
|
||||
To use **RC4** (Stream Cipher):
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
static_encrypt = { version = "0.1.0", features = ["rc4"] }
|
||||
|
||||
```
|
||||
|
||||
To use **XorR** (Rolling Key XOR - harder to crack):
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
static_encrypt = { version = "0.1.0", features = ["xorr"] }
|
||||
|
||||
```
|
||||
|
||||
## Supported Algorithms
|
||||
|
||||
Select one via `features` in `Cargo.toml`.
|
||||
|
||||
| Feature | Algorithm | Description | Strength |
|
||||
| --- | --- | --- | --- |
|
||||
| **`xor`** | **XOR (Default)** | Classic repeating-key XOR. | Low (Fastest) |
|
||||
| `rc4` | **RC4** | Rivest Cipher 4 (Stream Cipher). | Medium |
|
||||
| `xorshift` | **XorShift** | Uses a Pseudo-Random Number Generator (PRNG) as a keystream. | Medium |
|
||||
| `xorr` | **Rolling XOR** | Key bits rotate/roll after every byte. Prevents simple frequency analysis. | Medium-High |
|
||||
| `vigenere` | **Vigenère** | Polyalphabetic substitution (Addition/Subtraction). | Low |
|
||||
| `lcg` | **LCG** | Linear Congruential Generator stream. | Low-Medium |
|
||||
|
||||
## How It Works
|
||||
|
||||
1. **Build Script (`build.rs`):** When you run `cargo build`, this script runs first. It generates a high-entropy random key (64 bytes) and saves it into the compilation environment.
|
||||
2. **Macro Expansion:** The `enc!("string")` macro reads this key, encrypts your string using the selected algorithm (e.g., RC4), and replaces your string with a byte array: `[23, 114, 210, ...]`.
|
||||
3. **Runtime:** The `set_crypt!()` macro injects a tiny decryptor function. When your program runs, it takes the byte array and decrypts it back to a string in memory.
|
||||
|
||||
## License
|
||||
|
||||
- Apache License, Version 2.0, ([LICENSE-APACHE](./LICENSE-APACHE) or
|
||||
<https://www.apache.org/licenses/LICENSE-2.0>)
|
||||
- MIT license ([LICENSE-MIT](./LICENSE-MIT) or <https://opensource.org/licenses/MIT>)
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
use rand::{rngs::OsRng, TryRngCore};
|
||||
|
||||
fn main() {
|
||||
// gen random key on compile time
|
||||
let mut key = [0u8; 64];
|
||||
OsRng.try_fill_bytes(&mut key).unwrap();
|
||||
|
||||
let key_string = key
|
||||
.iter()
|
||||
.map(|b| b.to_string())
|
||||
.collect::<Vec<String>>()
|
||||
.join(",");
|
||||
|
||||
println!("cargo:rustc-env=LITCRYPT_KEY={}", key_string);
|
||||
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
}
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
// Smukx.E (@5mukx)
|
||||
|
||||
extern crate proc_macro;
|
||||
use proc_macro::{TokenStream, TokenTree};
|
||||
use quote::{quote};
|
||||
use proc_macro2::{Literal};
|
||||
|
||||
fn get_compile_time_key() -> Vec<u8> {
|
||||
let key_str = env!("LITCRYPT_KEY");
|
||||
key_str.split(',')
|
||||
.map(|s| s.parse::<u8>().expect("Failed to parse key from build.rs"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[proc_macro]
|
||||
pub fn set_crypt(_input: TokenStream) -> TokenStream {
|
||||
let decrypt_code = if cfg!(feature = "rc4") {
|
||||
emit_rc4_decrypt()
|
||||
} else if cfg!(feature = "xorshift") {
|
||||
emit_xorshift_decrypt()
|
||||
} else if cfg!(feature = "vigenere") {
|
||||
emit_vigenere_decrypt()
|
||||
} else if cfg!(feature = "lcg") {
|
||||
emit_lcg_decrypt()
|
||||
} else if cfg!(feature = "xorr") {
|
||||
emit_xorr_decrypt()
|
||||
} else {
|
||||
emit_xor_decrypt()
|
||||
};
|
||||
|
||||
let master_key = get_compile_time_key();
|
||||
let master_key_enc = encrypt_xor(&master_key, b"code/rustc/e5b2d8f9a1c3049687db03746cdf8af4d86e9ca4/library/alloc/src/vec/mod.rs");
|
||||
let master_key_lit = Literal::byte_string(&master_key_enc);
|
||||
|
||||
quote! {
|
||||
pub mod litcrypt_internal {
|
||||
pub fn decrypt_final(encrypted: &[u8]) -> String {
|
||||
let key_enc = #master_key_lit;
|
||||
|
||||
// Confuse while analysis =)
|
||||
let master_key = decrypt_xor_internal(key_enc, b"code/rustc/e5b2d8f9a1c3049687db03746cdf8af4d86e9ca4/library/alloc/src/vec/mod.rs");
|
||||
let decrypted_bytes = decrypt_bytes(encrypted, &master_key);
|
||||
String::from_utf8(decrypted_bytes).unwrap_or(String::from("???"))
|
||||
}
|
||||
|
||||
fn decrypt_xor_internal(source: &[u8], key: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(source.len());
|
||||
for (i, byte) in source.iter().enumerate() {
|
||||
out.push(byte ^ key[i % key.len()]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#decrypt_code
|
||||
}
|
||||
}.into()
|
||||
}
|
||||
|
||||
#[proc_macro]
|
||||
pub fn enc(tokens: TokenStream) -> TokenStream {
|
||||
let mut input_str = String::new();
|
||||
for tok in tokens {
|
||||
if let TokenTree::Literal(lit) = tok {
|
||||
let s = lit.to_string();
|
||||
|
||||
if s.starts_with("r") {
|
||||
if let Some(start_quote) = s.find('"') {
|
||||
let num_hashes = start_quote - 1;
|
||||
let end_quote = s.len() - 1 - num_hashes;
|
||||
input_str = s[start_quote + 1..end_quote].to_string();
|
||||
}
|
||||
} else if s.starts_with('"') {
|
||||
input_str = s.trim_matches('"').to_string();
|
||||
|
||||
input_str = input_str.replace("\\\"", "\"").replace("\\\\", "\\");
|
||||
} else {
|
||||
input_str = s;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let key = get_compile_time_key();
|
||||
|
||||
let encrypted_bytes = if cfg!(feature = "rc4") {
|
||||
encrypt_rc4(input_str.as_bytes(), &key)
|
||||
} else if cfg!(feature = "xorshift") {
|
||||
encrypt_xorshift(input_str.as_bytes(), &key)
|
||||
} else if cfg!(feature = "vigenere") {
|
||||
encrypt_vigenere(input_str.as_bytes(), &key)
|
||||
} else if cfg!(feature = "lcg") {
|
||||
encrypt_lcg(input_str.as_bytes(), &key)
|
||||
} else if cfg!(feature = "xorr") {
|
||||
encrypt_xorr(input_str.as_bytes(), &key)
|
||||
} else {
|
||||
encrypt_xor(input_str.as_bytes(), &key)
|
||||
};
|
||||
|
||||
let bytes_lit = Literal::byte_string(&encrypted_bytes);
|
||||
|
||||
quote! {
|
||||
crate::litcrypt_internal::decrypt_final(#bytes_lit)
|
||||
}.into()
|
||||
}
|
||||
|
||||
// encryption algorithm starts here .....
|
||||
fn encrypt_xor(source: &[u8], key: &[u8]) -> Vec<u8> {
|
||||
source.iter().enumerate().map(|(i, b)| b ^ key[i % key.len()]).collect()
|
||||
}
|
||||
|
||||
fn emit_xor_decrypt() -> proc_macro2::TokenStream {
|
||||
quote! {
|
||||
fn decrypt_bytes(source: &[u8], key: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(source.len());
|
||||
for (i, byte) in source.iter().enumerate() {
|
||||
out.push(byte ^ key[i % key.len()]);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn encrypt_rc4(data: &[u8], key: &[u8]) -> Vec<u8> {
|
||||
let mut s: [u8; 256] = [0; 256];
|
||||
let mut j: usize = 0;
|
||||
for i in 0..=255 { s[i] = i as u8; }
|
||||
for i in 0..=255 {
|
||||
j = (j + s[i] as usize + key[i % key.len()] as usize) % 256;
|
||||
s.swap(i, j);
|
||||
}
|
||||
let mut i = 0; j = 0;
|
||||
let mut out = Vec::new();
|
||||
for &b in data {
|
||||
i = (i + 1) % 256;
|
||||
j = (j + s[i] as usize) % 256;
|
||||
s.swap(i, j);
|
||||
let k = s[(s[i] as usize + s[j] as usize) % 256];
|
||||
out.push(b ^ k);
|
||||
}
|
||||
out
|
||||
}
|
||||
fn emit_rc4_decrypt() -> proc_macro2::TokenStream {
|
||||
quote! {
|
||||
fn decrypt_bytes(data: &[u8], key: &[u8]) -> Vec<u8> {
|
||||
let mut s: [u8; 256] = [0; 256];
|
||||
let mut j: usize = 0;
|
||||
for i in 0..=255 { s[i] = i as u8; }
|
||||
for i in 0..=255 {
|
||||
j = (j + s[i] as usize + key[i % key.len()] as usize) % 256;
|
||||
let tmp = s[i]; s[i] = s[j]; s[j] = tmp;
|
||||
}
|
||||
let mut i = 0; j = 0;
|
||||
let mut out = Vec::new();
|
||||
for &b in data {
|
||||
i = (i + 1) % 256;
|
||||
j = (j + s[i] as usize) % 256;
|
||||
let tmp = s[i]; s[i] = s[j]; s[j] = tmp;
|
||||
let k = s[(s[i] as usize + s[j] as usize) % 256];
|
||||
out.push(b ^ k);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn encrypt_xorshift(data: &[u8], key: &[u8]) -> Vec<u8> {
|
||||
let mut seed: u32 = 0xCAFEBABE;
|
||||
for &b in key { seed = seed.wrapping_add(b as u32).wrapping_mul(0x9E3779B9); }
|
||||
if seed == 0 { seed = 0xDEADBEEF; }
|
||||
let mut out = Vec::new();
|
||||
let mut state = seed;
|
||||
for &b in data {
|
||||
let mut x = state;
|
||||
x ^= x << 13; x ^= x >> 17; x ^= x << 5;
|
||||
state = x;
|
||||
out.push(b ^ (state as u8));
|
||||
}
|
||||
out
|
||||
}
|
||||
fn emit_xorshift_decrypt() -> proc_macro2::TokenStream {
|
||||
quote! {
|
||||
fn decrypt_bytes(data: &[u8], key: &[u8]) -> Vec<u8> {
|
||||
let mut seed: u32 = 0xCAFEBABE;
|
||||
for &b in key { seed = seed.wrapping_add(b as u32).wrapping_mul(0x9E3779B9); }
|
||||
if seed == 0 { seed = 0xDEADBEEF; }
|
||||
let mut out = Vec::new();
|
||||
let mut state = seed;
|
||||
for &b in data {
|
||||
let mut x = state;
|
||||
x ^= x << 13; x ^= x >> 17; x ^= x << 5;
|
||||
state = x;
|
||||
out.push(b ^ (state as u8));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn encrypt_vigenere(data: &[u8], key: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
for (i, &b) in data.iter().enumerate() {
|
||||
let k = key[i % key.len()];
|
||||
|
||||
out.push(b.wrapping_add(k));
|
||||
}
|
||||
out
|
||||
}
|
||||
fn emit_vigenere_decrypt() -> proc_macro2::TokenStream {
|
||||
quote! {
|
||||
fn decrypt_bytes(data: &[u8], key: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
for (i, &b) in data.iter().enumerate() {
|
||||
let k = key[i % key.len()];
|
||||
|
||||
out.push(b.wrapping_sub(k));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn encrypt_lcg(data: &[u8], key: &[u8]) -> Vec<u8> {
|
||||
let mut seed: u32 = 0;
|
||||
for &b in key { seed = seed.wrapping_add(b as u32); }
|
||||
|
||||
let a: u32 = 1664525;
|
||||
let c: u32 = 1013904223;
|
||||
let mut state = seed;
|
||||
|
||||
let mut out = Vec::new();
|
||||
for &b in data {
|
||||
state = state.wrapping_mul(a).wrapping_add(c);
|
||||
let pad = (state >> 24) as u8;
|
||||
out.push(b ^ pad);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn emit_lcg_decrypt() -> proc_macro2::TokenStream {
|
||||
quote! {
|
||||
fn decrypt_bytes(data: &[u8], key: &[u8]) -> Vec<u8> {
|
||||
let mut seed: u32 = 0;
|
||||
for &b in key { seed = seed.wrapping_add(b as u32); }
|
||||
|
||||
let a: u32 = 1664525;
|
||||
let c: u32 = 1013904223;
|
||||
let mut state = seed;
|
||||
|
||||
let mut out = Vec::new();
|
||||
for &b in data {
|
||||
state = state.wrapping_mul(a).wrapping_add(c);
|
||||
let pad = (state >> 24) as u8;
|
||||
out.push(b ^ pad);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn encrypt_xorr(data: &[u8], key: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let mut rolling_key = key.to_vec();
|
||||
let len = rolling_key.len();
|
||||
|
||||
for (i, &b) in data.iter().enumerate() {
|
||||
let idx = i % len;
|
||||
let k = rolling_key[idx];
|
||||
|
||||
out.push(b ^ k);
|
||||
|
||||
rolling_key[idx] = k.rotate_left(1);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn emit_xorr_decrypt() -> proc_macro2::TokenStream {
|
||||
quote! {
|
||||
fn decrypt_bytes(data: &[u8], key: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let mut rolling_key = key.to_vec();
|
||||
let len = rolling_key.len();
|
||||
|
||||
for (i, &b) in data.iter().enumerate() {
|
||||
let idx = i % len;
|
||||
let k = rolling_key[idx];
|
||||
|
||||
out.push(b ^ k);
|
||||
|
||||
rolling_key[idx] = k.rotate_left(1);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
#[macro_use]
|
||||
extern crate static_encrypt;
|
||||
|
||||
set_crypt!();
|
||||
|
||||
#[test]
|
||||
fn basic_ascii() {
|
||||
let plain = "Hello World";
|
||||
let enc = enc!("Hello World");
|
||||
assert_eq!(plain, enc);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_raw_string() {
|
||||
let json = r#"{"status": "ok", "code": 200}"#;
|
||||
let enc = enc!(r#"{"status": "ok", "code": 200}"#);
|
||||
assert_eq!(json, enc);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn japanese_kanji_hiragana() {
|
||||
let plain = "こんにちは世界";
|
||||
let enc = enc!("こんにちは世界");
|
||||
assert_eq!(plain, enc);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chinese_simplified() {
|
||||
let plain = "加密很有趣";
|
||||
let enc = enc!("加密很有趣");
|
||||
assert_eq!(plain, enc);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn russian_cyrillic() {
|
||||
let plain = "Rust - это быстро";
|
||||
let enc = enc!("Rust - это быстро");
|
||||
assert_eq!(plain, enc);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn robust_special_chars() {
|
||||
let plain = "Key: !@#$%^&*()_+|~=`{}[]:\";'<>?,./ ⚠️";
|
||||
let enc_simple = enc!("Key: !@#$%^&*()_+|~=`{}[]:\";'<>?,./ ⚠️");
|
||||
assert_eq!(plain, enc_simple);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_languages() {
|
||||
let plain = "Hello - こんにちは - 你好 - Привет";
|
||||
let enc = enc!("Hello - こんにちは - 你好 - Привет");
|
||||
assert_eq!(plain, enc);
|
||||
}
|
||||
Reference in New Issue
Block a user