Skip to content

Instantly share code, notes, and snippets.

@lordgatto
Created June 12, 2025 16:43
Show Gist options
  • Save lordgatto/e0a03351b253181aed2007ac88b88d07 to your computer and use it in GitHub Desktop.
Save lordgatto/e0a03351b253181aed2007ac88b88d07 to your computer and use it in GitHub Desktop.
package net.lordgatto.Functions;
import java.util.Base64;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import java.security.spec.*;
public class Coder {
private static final int KEY_SIZE = 256;
private static final int IV_SIZE = 16;
private static final int SALT_SIZE = 16;
private static final int ITERATIONS = 65536;
public static byte[] generateRandomBytes(int lenght) {
byte[] bytes = new byte[lenght];
new SecureRandom().nextBytes(bytes);
return bytes;
}
public static SecretKeySpec deriveKeyFromPassword(String password, byte[] salt) throws Exception {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, ITERATIONS, KEY_SIZE);
byte[] KeyBytes = factory.generateSecret(spec).getEncoded();
return new SecretKeySpec(KeyBytes, "AES");
}
public static byte[] encrypt(String text, String password) throws Exception {
byte[] salt = generateRandomBytes(SALT_SIZE);
byte[] iv = generateRandomBytes(IV_SIZE);
SecretKeySpec key = deriveKeyFromPassword(password, salt);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
byte[] encrypted = cipher.doFinal(text.getBytes());
byte[] combined = new byte[salt.length + iv.length + encrypted.length];
System.arraycopy(salt, 0, combined, 0, salt.length);
System.arraycopy(iv, 0, combined, salt.length, iv.length);
System.arraycopy(encrypted, 0, combined, salt.length + iv.length, encrypted.length);
return combined;
}
public static String decrypt(byte[] text, String password) throws Exception {
byte[] salt = new byte[SALT_SIZE];
byte[] iv = new byte[IV_SIZE];
byte[] ciphed = new byte[text.length - ( SALT_SIZE + IV_SIZE )];
System.arraycopy(text, 0, salt, 0, SALT_SIZE);
System.arraycopy(text, SALT_SIZE, iv, 0, IV_SIZE);
System.arraycopy(text, SALT_SIZE + IV_SIZE, ciphed, 0, ciphed.length);
SecretKeySpec key = deriveKeyFromPassword(password, salt);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
byte[] decrypted = cipher.doFinal(ciphed);
return new String(decrypted);
}
public static String Code(String decoded) {
return Base64.getEncoder().encodeToString(decoded.getBytes());
}
public static String Decode(String encoded) {
return new String(Base64.getDecoder().decode(encoded));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment