mirror of
https://github.com/xiaozhou233/JuiceAgent.git
synced 2026-12-05 13:05:53 +08:00
Restore: re-add README, examples and tools
This commit is contained in:
1 parent
6e417035b6
commit
57405e810c
16 files changed
+825
No files matched your search
@@ -0,0 +1,230 @@
|
||||
# JuiceAgent
|
||||
|
||||
JuiceAgent is an advanced JVMTI-based injection framework for runtime JAR loading, bytecode transformation, and runtime JVM instrumentation. It injects into a running JVM process even when `DisableAttachMechanism=true`, without requiring `-javaagent` startup arguments or the attach mechanism.
|
||||
|
||||
**Warning**: This project is still experimental and is not recommended for production use. Use it at your own risk.
|
||||
|
||||
**Note**: This project is designed for a regular JVM. Custom JVMs may not be able to run it.
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
## Index
|
||||
|
||||
- [JuiceAgent](#juiceagent)
|
||||
- [Introduction](#introduction)
|
||||
- [How It Works](#how-it-works)
|
||||
- [Features](#features)
|
||||
- [Project Structure](#project-structure)
|
||||
- [Quick Start](#quick-start)
|
||||
- [JuiceAgent API](#juiceagent-api)
|
||||
- [Examples](#examples)
|
||||
- [How To Build](#how-to-build)
|
||||
- [Full Disclaimer](#full-disclaimer)
|
||||
- [Acknowledgements](#acknowledgements)
|
||||
|
||||
## Introduction
|
||||
|
||||
JuiceAgent is the native implementation of the [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API). It loads external JARs into a running JVM, invokes a specified entry class/method, and redefines or retransforms already-loaded classes — all without a `-javaagent` startup flag and even when `DisableAttachMechanism=true`.
|
||||
|
||||
With JuiceAgent, developers can:
|
||||
|
||||
- Dynamically load external JARs into a running JVM process
|
||||
- Invoke a specified entry class and method after injection
|
||||
- Redefine already loaded classes at runtime
|
||||
- Retransform bytecode for instrumentation or modification
|
||||
- Query loaded classes and read class bytecode
|
||||
|
||||
**If you have any questions or suggestions, please feel free to open an issue or submit a pull request. =D**
|
||||
|
||||
## How It Works
|
||||
|
||||
1. `injector.exe` (or `libinject.dll` via JNI) reflectively injects `libloader.dll` into the target JVM process.
|
||||
2. `libloader.dll` attaches to the JVM, reads `config.toml`, extracts the embedded `JuiceAgent-API` jar, and adds it to the system class loader search path.
|
||||
3. The loader bootstraps the agent: it loads `libagent.dll` and initializes the JVMTI agent (`JuiceAgent::Agent`).
|
||||
4. The agent registers JVMTI callbacks and starts the configured modules (e.g. `JarLoader`), which loads the target JAR and invokes the entry class/method.
|
||||
|
||||
The `JuiceAgent-API` jar is embedded in the native binaries, so no separate download is required.
|
||||
|
||||
## Features
|
||||
|
||||
- Load external JARs into the Bootstrap or System ClassLoader
|
||||
- Add JARs to an arbitrary class loader
|
||||
- Define classes dynamically
|
||||
- Redefine classes by name or class reference
|
||||
- Retransform classes by name or class reference
|
||||
- Get all loaded classes
|
||||
- Find a class by name
|
||||
- Get class bytecode by name or class reference
|
||||
- Automatic JVM attachment that works with `DisableAttachMechanism=true`
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `src/libloader` — `libloader.dll`. Injected into the target JVM. Attaches to the JVM, parses `config.toml`, injects the embedded `JuiceAgent-API`, and bootstraps the agent.
|
||||
- `src/libagent` — `libagent.dll`. The JVMTI agent. Registers callbacks (e.g. `ClassFileLoadHook`) and implements the native side of `JuiceAgent-API`.
|
||||
- `src/libinjector` — `injector.exe` + `libinject.dll`. Reflective DLL injector that loads `libloader.dll` into the target process. Can be driven from the command line or through JNI.
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Download Release
|
||||
|
||||
Download `JuiceAgent_vx.x.x_x64.zip` from the [releases](https://github.com/xiaozhou233/JuiceAgent/releases) page.
|
||||
|
||||
Extract the ZIP file to a directory:
|
||||
|
||||
- YourDir
|
||||
- libagent.dll
|
||||
- libinject.dll
|
||||
- libloader.dll
|
||||
- injector.exe
|
||||
|
||||
### 2. Copy your Custom JAR / Dependencies
|
||||
|
||||
- YourDir
|
||||
- libagent.dll
|
||||
- libinject.dll
|
||||
- libloader.dll
|
||||
- injector.exe
|
||||
- **MyCustomJar.jar**
|
||||
- **injection**
|
||||
- **Dependencies1.jar**
|
||||
- **Dependencies2.jar**
|
||||
|
||||
### 3. Write Config
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
# Path to libagent.dll, default is "./libagent.dll"
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
Enabled = true
|
||||
# Directory containing dependency JARs to load first
|
||||
InjectionDir = "./injection"
|
||||
# Path to the JAR file to be loaded
|
||||
JarPath = "./MyCustomJar.jar"
|
||||
# Entry class to be executed after loading the JAR
|
||||
EntryClass = "Example.Main"
|
||||
# Entry method, must be: public static void run()
|
||||
EntryMethod = "run"
|
||||
```
|
||||
|
||||
Save the file as `config.toml` in the same directory (the runtime directory). Relative paths are resolved against the runtime directory.
|
||||
|
||||
- YourDir
|
||||
- **config.toml**
|
||||
- libagent.dll
|
||||
- libinject.dll
|
||||
- libloader.dll
|
||||
- injector.exe
|
||||
- MyCustomJar.jar
|
||||
- injection
|
||||
- Dependencies1.jar
|
||||
- Dependencies2.jar
|
||||
|
||||
### 4. Run the Injector
|
||||
|
||||
#### Method A: Use `injector.exe`
|
||||
|
||||
Run `injector.exe` from `YourDir`:
|
||||
|
||||
```text
|
||||
<jps output>
|
||||
Input PID:
|
||||
```
|
||||
|
||||
Enter the PID of the target JVM process and press Enter.
|
||||
|
||||
You can also pass arguments directly: `injector.exe <pid> <libloader.dll path> [libinject.dll path]`.
|
||||
|
||||
#### Method B: Use JNI to call `inject`
|
||||
|
||||
See [docs/Inject.md](docs/Inject.md) for details.
|
||||
|
||||
### 5. Done
|
||||
|
||||
The target JVM will load the specified JAR and execute the specified entry class and method.
|
||||
|
||||
## JuiceAgent API
|
||||
|
||||
The following native functions are exposed to Java through the `cn.xiaozhou233.juiceagent.api.JuiceAgent` class (see the [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API) project for the Java API definition):
|
||||
|
||||
- `init(String runtimeDir)` — initialize the agent from Java
|
||||
- `addToBootstrapClassLoaderSearch(String jarPath)`
|
||||
- `addToSystemClassLoaderSearch(String jarPath)`
|
||||
- `addToClassLoader(String jarPath, ClassLoader targetClassLoader)`
|
||||
- `defineClass(ClassLoader targetClassLoader, byte[] bytes)` — returns `Class<?>`
|
||||
- `redefineClass(Class<?> clazz, byte[] classBytes, int length)`
|
||||
- `redefineClassByName(String className, byte[] classBytes, int length)`
|
||||
- `retransformClass(Class<?> clazz, byte[] bytecodes, int length)`
|
||||
- `retransformClassByName(String className, byte[] bytecodes, int length)`
|
||||
- `getLoadedClasses()` — returns `Class<?>[]`
|
||||
- `getClassByName(String name)` — returns `Class<?>`
|
||||
- `getClassBytes(Class<?> clazz)` — returns `byte[]`
|
||||
- `getClassBytesByName(String name)` — returns `byte[]`
|
||||
|
||||
## Examples
|
||||
|
||||
- `examples/load-via-injector-exe` — loads a JAR into a target JVM via `injector.exe` and runs an entry point.
|
||||
- `examples/retansform-class` — demonstrates class retransformation with a target JVM and a modified copy of the class.
|
||||
|
||||
## How To Build
|
||||
|
||||
### Requirements
|
||||
|
||||
- Java 8+
|
||||
- MinGW
|
||||
- CMake 3.15+
|
||||
- Ninja
|
||||
|
||||
### Build with CMake Presets
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/xiaozhou233/JuiceAgent.git
|
||||
cd JuiceAgent
|
||||
|
||||
cmake --preset ninja-release
|
||||
cmake --build build
|
||||
```
|
||||
|
||||
### Manual Build
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/xiaozhou233/JuiceAgent.git
|
||||
cd JuiceAgent
|
||||
|
||||
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build
|
||||
```
|
||||
|
||||
The generated binaries will be placed in `build/bin`.
|
||||
|
||||
## Full Disclaimer
|
||||
|
||||
This project is intended for learning and research in controlled environments only. The author is not responsible for any consequences arising from unauthorized use, modification, cracking, or violation of any applicable agreements or laws. Users are responsible for ensuring that their actions are legal and compliant.
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
- [ReflectiveDLLInjection](https://github.com/stephenfewer/ReflectiveDLLInjection) — DLL injection implementation
|
||||
- [plog](https://github.com/SergiusTheBest/plog) — Portable, simple, and extensible C++ logging library
|
||||
- [toml11](https://github.com/ToruNiina/toml11) — TOML for Modern C++
|
||||
- [eventpp](https://github.com/wqking/eventpp) — C++ library for event dispatchers and callback lists
|
||||
@@ -0,0 +1,9 @@
|
||||
# Temporary build directories
|
||||
**/out/*
|
||||
**/*.class
|
||||
|
||||
# JuiceAgent runtime binaries copied into the example (not committed)
|
||||
load-via-injector-exe/injector.exe
|
||||
load-via-injector-exe/libagent.dll
|
||||
load-via-injector-exe/libinject.dll
|
||||
load-via-injector-exe/libloader.dll
|
||||
@@ -0,0 +1,65 @@
|
||||
============================================
|
||||
HowToUse
|
||||
============================================
|
||||
|
||||
Prerequisites: Java 8+ (javac/jar for building, jps for injection)
|
||||
|
||||
Directory Files:
|
||||
injector.exe libagent.dll libinject.dll libloader.dll - JuiceAgent runtime
|
||||
config.toml - injection config
|
||||
demo.jar - JAR to inject (built by build.bat)
|
||||
target.jar - target JVM program (built by build.bat)
|
||||
injection/ - injection source
|
||||
target/ - target source
|
||||
build.bat - rebuild demo.jar / target.jar
|
||||
run.bat - run target JVM (target.jar)
|
||||
|
||||
============================================
|
||||
Usage Steps
|
||||
============================================
|
||||
|
||||
1. Build (optional)
|
||||
demo.jar and target.jar are already included by default.
|
||||
If you modified injection/Main.java or target/target.java, run:
|
||||
build.bat
|
||||
to regenerate demo.jar and target.jar in this directory.
|
||||
|
||||
2. Run the target JVM
|
||||
Double-click run.bat (or run: java -jar target.jar). A black window
|
||||
appears and prints:
|
||||
[Target] I am the target JVM (PID: <PID>)
|
||||
...... (once per second)
|
||||
|
||||
3. Inject
|
||||
Double-click injector.exe, type the target PID and press Enter:
|
||||
6644 target.jar
|
||||
10504 jdk.jcmd/sun.tools.jps.Jps
|
||||
Input PID: 6644
|
||||
|
||||
4. Verify
|
||||
Go back to the target window. Injection succeeded if you see:
|
||||
[Demo] Injection succeeded! Hello from JuiceAgent.
|
||||
[Demo] Current thread: Thread-0
|
||||
|
||||
============================================
|
||||
Config / config.toml
|
||||
============================================
|
||||
|
||||
JarPath - JAR path to inject (default: ./demo.jar)
|
||||
EntryClass - Entry class (default: Example.Main)
|
||||
EntryMethod - Entry method, must be public static void run()
|
||||
InjectionDir - Dependency JAR directory (only *.jar is loaded)
|
||||
|
||||
============================================
|
||||
Troubleshooting
|
||||
============================================
|
||||
|
||||
- "java/javac/jar is not recognized":
|
||||
Install a JDK and add its bin directory to PATH.
|
||||
- injector.exe reports injection failure:
|
||||
Make sure the target JVM is running and the PID is correct.
|
||||
- No [Demo] output appears:
|
||||
The target window prints many log lines which may affect reading.
|
||||
Check the [JuiceAgent JarLoader] lines to locate the cause.
|
||||
If it still fails, copy the full log and submit an Issue, or paste
|
||||
it directly to an AI.
|
||||
@@ -0,0 +1,23 @@
|
||||
@echo off
|
||||
echo === Building injection jar ===
|
||||
pushd injection
|
||||
call build.bat
|
||||
popd
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
echo.
|
||||
echo === Building target jar ===
|
||||
pushd target
|
||||
call build.bat
|
||||
popd
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
echo.
|
||||
echo Build finished: demo.jar and target.jar are in this directory.
|
||||
goto :end
|
||||
|
||||
:error
|
||||
echo Build failed.
|
||||
exit /b 1
|
||||
|
||||
:end
|
||||
@@ -0,0 +1,21 @@
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
# Path to JuiceAgent-API jar, leave empty to use the built-in API
|
||||
JuiceAgentAPIJarPath = ""
|
||||
# Path to libagent.dll, default is "./libagent.dll"
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
Enabled = true
|
||||
# Directory containing dependency JARs to load into the JVM (put your deps here)
|
||||
InjectionDir = "./injection"
|
||||
# Path to the injection JAR to be loaded
|
||||
JarPath = "./demo.jar"
|
||||
# Entry class to be executed after loading the JAR
|
||||
EntryClass = "Example.Main"
|
||||
# Entry method, must be: public static void run()
|
||||
EntryMethod = "run"
|
||||
Binary file not shown.
@@ -0,0 +1,8 @@
|
||||
package Example;
|
||||
|
||||
public class Main {
|
||||
public static void run() {
|
||||
System.out.println("[Demo] Injection succeeded! Hello from JuiceAgent.");
|
||||
System.out.println("[Demo] Current thread: " + Thread.currentThread().getName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
@echo off
|
||||
setlocal
|
||||
|
||||
set "SRC=Main.java"
|
||||
set "OUT=out"
|
||||
set "JAR=..\demo.jar"
|
||||
|
||||
if exist "%OUT%" rmdir /s /q "%OUT%"
|
||||
if exist "%JAR%" del /q "%JAR%"
|
||||
|
||||
mkdir "%OUT%"
|
||||
javac -encoding UTF-8 --release 8 -d "%OUT%" "%SRC%"
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
jar --create --file "%JAR%" -C "%OUT%" .
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
rmdir /s /q "%OUT%"
|
||||
|
||||
echo Build succeeded: demo.jar
|
||||
goto :end
|
||||
|
||||
:error
|
||||
echo Build failed.
|
||||
exit /b 1
|
||||
|
||||
:end
|
||||
endlocal
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
cd /d "%~dp0"
|
||||
java -jar target.jar
|
||||
pause
|
||||
Binary file not shown.
@@ -0,0 +1,28 @@
|
||||
@echo off
|
||||
setlocal
|
||||
|
||||
set "SRC=target.java"
|
||||
set "OUT=out"
|
||||
set "JAR=..\target.jar"
|
||||
|
||||
if exist "%OUT%" rmdir /s /q "%OUT%"
|
||||
if exist "%JAR%" del /q "%JAR%"
|
||||
|
||||
mkdir "%OUT%"
|
||||
javac -encoding UTF-8 --release 8 -d "%OUT%" "%SRC%"
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
jar --create --file "%JAR%" --main-class target -C "%OUT%" .
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
rmdir /s /q "%OUT%"
|
||||
|
||||
echo Build succeeded: target.jar
|
||||
goto :end
|
||||
|
||||
:error
|
||||
echo Build failed.
|
||||
exit /b 1
|
||||
|
||||
:end
|
||||
endlocal
|
||||
@@ -0,0 +1,15 @@
|
||||
import java.lang.management.ManagementFactory;
|
||||
|
||||
public class target {
|
||||
public static void main(String[] args) {
|
||||
String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
|
||||
try {
|
||||
while (true) {
|
||||
System.out.println("[Target] I am the target JVM (PID: " + pid + ")");
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
============================================
|
||||
使用说明 / HOW TO USE
|
||||
============================================
|
||||
|
||||
前提条件:已安装 Java 8+(需要 javac/jar 构建,jps 用于注入)
|
||||
|
||||
目录文件说明:
|
||||
injector.exe libagent.dll libinject.dll libloader.dll - JuiceAgent 运行时
|
||||
config.toml - 注入配置
|
||||
demo.jar - 待注入的 JAR(build.bat 生成)
|
||||
target.jar - 目标 JVM 程序(build.bat 生成)
|
||||
injection/ - 注入代码源码
|
||||
target/ - 目标程序源码
|
||||
build.bat - 重新生成 demo.jar / target.jar
|
||||
run.bat - 运行目标 JVM(target.jar)
|
||||
|
||||
============================================
|
||||
使用步骤 / Usage Steps
|
||||
============================================
|
||||
|
||||
1. 构建(可选)
|
||||
默认已包含 demo.jar 和 target.jar。
|
||||
若修改了 injection/Main.java 或 target/target.java,请运行:
|
||||
build.bat
|
||||
生成 demo.jar 和 target.jar 到本目录。
|
||||
|
||||
2. 运行目标 JVM
|
||||
双击 run.bat(或执行 java -jar target.jar),出现黑色窗口并输出:
|
||||
[Target] I am the target JVM (PID: <PID>)
|
||||
......(每秒输出一次)
|
||||
|
||||
3. 注入
|
||||
双击 injector.exe,出现黑色窗口,输入目标 PID 并回车:
|
||||
6644 target.jar
|
||||
10504 jdk.jcmd/sun.tools.jps.Jps
|
||||
Input PID: 6644
|
||||
|
||||
4. 验证
|
||||
回到目标窗口,看到以下输出即注入成功:
|
||||
[Demo] Injection succeeded! Hello from JuiceAgent.
|
||||
[Demo] Current thread: Thread-0
|
||||
|
||||
============================================
|
||||
配置说明 / config.toml
|
||||
============================================
|
||||
|
||||
JarPath - 待注入的 JAR 路径(默认 ./demo.jar)
|
||||
EntryClass - 入口类(默认 Example.Main)
|
||||
EntryMethod - 入口方法,需为 public static void run()
|
||||
InjectionDir - 依赖 JAR 目录(仅加载 *.jar)
|
||||
|
||||
============================================
|
||||
常见问题 / Troubleshooting
|
||||
============================================
|
||||
|
||||
- "java/javac/jar 不是内部或外部命令":
|
||||
安装 JDK 并将其 bin 目录加入 PATH。
|
||||
- injector.exe 提示注入失败:
|
||||
确认目标 JVM 正在运行,且输入的 PID 正确。
|
||||
- 没有出现 [Demo] 输出:
|
||||
目标窗口会有大量日志,可能影响阅读;请查看其中的
|
||||
[JuiceAgent JarLoader] 日志定位原因。
|
||||
如仍无法解决,请复制完整日志提交 Issue,或直接丢给 AI。
|
||||
@@ -0,0 +1,4 @@
|
||||
*.h
|
||||
*.hpp
|
||||
JuiceAgent-API*.jar
|
||||
*.class
|
||||
@@ -0,0 +1,327 @@
|
||||
/*
|
||||
* File: file2bytes.cpp
|
||||
* Description:
|
||||
* Converts any file to a C++ byte array header with:
|
||||
* - MIME / type metadata
|
||||
* - SHA-256 hash
|
||||
* - Namespace wrapping
|
||||
*
|
||||
* Build:
|
||||
* g++ -std=c++17 file2bytes.cpp -o file2bytes
|
||||
*
|
||||
* Usage:
|
||||
* file2bytes <input_file> <output.hpp> [var_name] [namespace]
|
||||
*
|
||||
* Example:
|
||||
* file2bytes JuiceRemapper.jar payload.hpp jar_data Resource
|
||||
*/
|
||||
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <iomanip>
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include <cstdint>
|
||||
|
||||
static std::string getFileName(const std::string& path) {
|
||||
std::size_t pos = path.find_last_of("/\\");
|
||||
if (pos == std::string::npos)
|
||||
return path;
|
||||
return path.substr(pos + 1);
|
||||
}
|
||||
|
||||
static std::string getExtension(const std::string& fileName) {
|
||||
std::size_t pos = fileName.find_last_of('.');
|
||||
if (pos == std::string::npos)
|
||||
return "";
|
||||
return fileName.substr(pos + 1);
|
||||
}
|
||||
|
||||
static std::string toLower(std::string s) {
|
||||
for (char& c : s) {
|
||||
if (c >= 'A' && c <= 'Z')
|
||||
c = static_cast<char>(c - 'A' + 'a');
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
static std::string detectMime(const std::string& fileName) {
|
||||
std::string ext = toLower(getExtension(fileName));
|
||||
|
||||
if (ext == "jar") return "application/java-archive";
|
||||
if (ext == "zip") return "application/zip";
|
||||
if (ext == "json") return "application/json";
|
||||
if (ext == "txt") return "text/plain";
|
||||
if (ext == "xml") return "application/xml";
|
||||
if (ext == "png") return "image/png";
|
||||
if (ext == "jpg" || ext == "jpeg") return "image/jpeg";
|
||||
if (ext == "gif") return "image/gif";
|
||||
if (ext == "dll") return "application/x-msdownload";
|
||||
if (ext == "so") return "application/octet-stream";
|
||||
if (ext == "class") return "application/java-vm";
|
||||
|
||||
return "application/octet-stream";
|
||||
}
|
||||
|
||||
/* =========================
|
||||
Minimal SHA-256
|
||||
Public domain style impl
|
||||
========================= */
|
||||
|
||||
struct SHA256_CTX {
|
||||
uint8_t data[64];
|
||||
uint32_t datalen;
|
||||
uint64_t bitlen;
|
||||
uint32_t state[8];
|
||||
};
|
||||
|
||||
static uint32_t rotr(uint32_t x, uint32_t n) {
|
||||
return (x >> n) | (x << (32 - n));
|
||||
}
|
||||
|
||||
static uint32_t ch(uint32_t x, uint32_t y, uint32_t z) {
|
||||
return (x & y) ^ (~x & z);
|
||||
}
|
||||
|
||||
static uint32_t maj(uint32_t x, uint32_t y, uint32_t z) {
|
||||
return (x & y) ^ (x & z) ^ (y & z);
|
||||
}
|
||||
|
||||
static uint32_t ep0(uint32_t x) {
|
||||
return rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22);
|
||||
}
|
||||
|
||||
static uint32_t ep1(uint32_t x) {
|
||||
return rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25);
|
||||
}
|
||||
|
||||
static uint32_t sig0(uint32_t x) {
|
||||
return rotr(x, 7) ^ rotr(x, 18) ^ (x >> 3);
|
||||
}
|
||||
|
||||
static uint32_t sig1(uint32_t x) {
|
||||
return rotr(x, 17) ^ rotr(x, 19) ^ (x >> 10);
|
||||
}
|
||||
|
||||
static const uint32_t k[64] = {
|
||||
0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,
|
||||
0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
|
||||
0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,
|
||||
0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
|
||||
0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,
|
||||
0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
|
||||
0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,
|
||||
0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
|
||||
0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,
|
||||
0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
|
||||
0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,
|
||||
0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
|
||||
0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,
|
||||
0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
|
||||
0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,
|
||||
0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
|
||||
};
|
||||
|
||||
static void sha256_transform(SHA256_CTX* ctx, const uint8_t data[]) {
|
||||
uint32_t a,b,c,d,e,f,g,h,i,j,t1,t2,m[64];
|
||||
|
||||
for (i = 0, j = 0; i < 16; ++i, j += 4)
|
||||
m[i] = (data[j] << 24) | (data[j+1] << 16) |
|
||||
(data[j+2] << 8) | (data[j+3]);
|
||||
|
||||
for (; i < 64; ++i)
|
||||
m[i] = sig1(m[i-2]) + m[i-7] + sig0(m[i-15]) + m[i-16];
|
||||
|
||||
a = ctx->state[0];
|
||||
b = ctx->state[1];
|
||||
c = ctx->state[2];
|
||||
d = ctx->state[3];
|
||||
e = ctx->state[4];
|
||||
f = ctx->state[5];
|
||||
g = ctx->state[6];
|
||||
h = ctx->state[7];
|
||||
|
||||
for (i = 0; i < 64; ++i) {
|
||||
t1 = h + ep1(e) + ch(e,f,g) + k[i] + m[i];
|
||||
t2 = ep0(a) + maj(a,b,c);
|
||||
|
||||
h = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = d + t1;
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = t1 + t2;
|
||||
}
|
||||
|
||||
ctx->state[0] += a;
|
||||
ctx->state[1] += b;
|
||||
ctx->state[2] += c;
|
||||
ctx->state[3] += d;
|
||||
ctx->state[4] += e;
|
||||
ctx->state[5] += f;
|
||||
ctx->state[6] += g;
|
||||
ctx->state[7] += h;
|
||||
}
|
||||
|
||||
static void sha256_init(SHA256_CTX* ctx) {
|
||||
ctx->datalen = 0;
|
||||
ctx->bitlen = 0;
|
||||
ctx->state[0] = 0x6a09e667;
|
||||
ctx->state[1] = 0xbb67ae85;
|
||||
ctx->state[2] = 0x3c6ef372;
|
||||
ctx->state[3] = 0xa54ff53a;
|
||||
ctx->state[4] = 0x510e527f;
|
||||
ctx->state[5] = 0x9b05688c;
|
||||
ctx->state[6] = 0x1f83d9ab;
|
||||
ctx->state[7] = 0x5be0cd19;
|
||||
}
|
||||
|
||||
static void sha256_update(SHA256_CTX* ctx, const uint8_t data[], size_t len) {
|
||||
for (size_t i = 0; i < len; ++i) {
|
||||
ctx->data[ctx->datalen++] = data[i];
|
||||
if (ctx->datalen == 64) {
|
||||
sha256_transform(ctx, ctx->data);
|
||||
ctx->bitlen += 512;
|
||||
ctx->datalen = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void sha256_final(SHA256_CTX* ctx, uint8_t hash[]) {
|
||||
uint32_t i = ctx->datalen;
|
||||
|
||||
if (ctx->datalen < 56) {
|
||||
ctx->data[i++] = 0x80;
|
||||
while (i < 56) ctx->data[i++] = 0x00;
|
||||
} else {
|
||||
ctx->data[i++] = 0x80;
|
||||
while (i < 64) ctx->data[i++] = 0x00;
|
||||
sha256_transform(ctx, ctx->data);
|
||||
std::fill(ctx->data, ctx->data + 56, 0);
|
||||
}
|
||||
|
||||
ctx->bitlen += ctx->datalen * 8;
|
||||
ctx->data[63] = ctx->bitlen;
|
||||
ctx->data[62] = ctx->bitlen >> 8;
|
||||
ctx->data[61] = ctx->bitlen >> 16;
|
||||
ctx->data[60] = ctx->bitlen >> 24;
|
||||
ctx->data[59] = ctx->bitlen >> 32;
|
||||
ctx->data[58] = ctx->bitlen >> 40;
|
||||
ctx->data[57] = ctx->bitlen >> 48;
|
||||
ctx->data[56] = ctx->bitlen >> 56;
|
||||
sha256_transform(ctx, ctx->data);
|
||||
|
||||
for (i = 0; i < 4; ++i) {
|
||||
hash[i] = (ctx->state[0] >> (24 - i * 8)) & 0xff;
|
||||
hash[i + 4] = (ctx->state[1] >> (24 - i * 8)) & 0xff;
|
||||
hash[i + 8] = (ctx->state[2] >> (24 - i * 8)) & 0xff;
|
||||
hash[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0xff;
|
||||
hash[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0xff;
|
||||
hash[i + 20] = (ctx->state[5] >> (24 - i * 8)) & 0xff;
|
||||
hash[i + 24] = (ctx->state[6] >> (24 - i * 8)) & 0xff;
|
||||
hash[i + 28] = (ctx->state[7] >> (24 - i * 8)) & 0xff;
|
||||
}
|
||||
}
|
||||
|
||||
static std::string sha256Hex(const std::vector<unsigned char>& data) {
|
||||
SHA256_CTX ctx{};
|
||||
sha256_init(&ctx);
|
||||
sha256_update(&ctx, data.data(), data.size());
|
||||
|
||||
uint8_t hash[32];
|
||||
sha256_final(&ctx, hash);
|
||||
|
||||
std::ostringstream oss;
|
||||
for (int i = 0; i < 32; ++i) {
|
||||
oss << std::hex
|
||||
<< std::setw(2)
|
||||
<< std::setfill('0')
|
||||
<< static_cast<int>(hash[i]);
|
||||
}
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
if (argc < 3) {
|
||||
std::cout << "Usage: file2bytes <input_file> <output.hpp> [var_name] [namespace]\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
const char* input = argv[1];
|
||||
const char* output = argv[2];
|
||||
|
||||
std::string varName = (argc >= 4) ? argv[3] : "bytes";
|
||||
std::string ns = (argc >= 5) ? argv[4] : "Embedded";
|
||||
|
||||
std::string fileName = getFileName(input);
|
||||
std::string mime = detectMime(fileName);
|
||||
|
||||
std::ifstream in(input, std::ios::binary | std::ios::ate);
|
||||
if (!in) {
|
||||
std::cerr << "Failed to open input file: " << input << "\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
std::streamsize size = in.tellg();
|
||||
in.seekg(0, std::ios::beg);
|
||||
|
||||
std::vector<unsigned char> data(size);
|
||||
if (!in.read(reinterpret_cast<char*>(data.data()), size)) {
|
||||
std::cerr << "Failed to read file\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
std::string hash = sha256Hex(data);
|
||||
|
||||
std::ofstream out(output, std::ios::binary);
|
||||
if (!out) {
|
||||
std::cerr << "Failed to open output file: " << output << "\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
out << "#pragma once\n\n";
|
||||
out << "#include <cstddef>\n\n";
|
||||
|
||||
out << "namespace " << ns << " {\n\n";
|
||||
|
||||
out << "static const unsigned char " << varName << "[] = {\n";
|
||||
|
||||
for (std::size_t i = 0; i < data.size(); ++i) {
|
||||
if (i % 12 == 0)
|
||||
out << " ";
|
||||
|
||||
out << "0x"
|
||||
<< std::hex
|
||||
<< std::setw(2)
|
||||
<< std::setfill('0')
|
||||
<< static_cast<int>(data[i]);
|
||||
|
||||
if (i + 1 != data.size())
|
||||
out << ", ";
|
||||
|
||||
if (i % 12 == 11)
|
||||
out << "\n";
|
||||
}
|
||||
|
||||
out << "\n};\n\n";
|
||||
|
||||
out << "static const std::size_t " << varName << "_len = "
|
||||
<< std::dec << data.size() << ";\n";
|
||||
|
||||
out << "static const char* " << varName << "_name = "
|
||||
<< "\"" << fileName << "\";\n";
|
||||
|
||||
out << "static const char* " << varName << "_mime = "
|
||||
<< "\"" << mime << "\";\n";
|
||||
|
||||
out << "static const char* " << varName << "_sha256 = "
|
||||
<< "\"" << hash << "\";\n";
|
||||
|
||||
out << "\n} // namespace " << ns << "\n";
|
||||
|
||||
std::cout << "Generated: " << output << "\n";
|
||||
return 0;
|
||||
}
|
||||
Binary file not shown.
Reference in new issue
Block a user