Java暴力破解案例

wen java案例 1

本文目录导读:

Java暴力破解案例

  1. 密码暴力破解案例
  2. 算法问题暴力求解
  3. 实际应用示例:验证码破解
  4. 优化技巧和注意事项

我来为您详细介绍Java暴力破解的典型案例,主要从密码破解和算法问题求解两个角度展开。

密码暴力破解案例

1 简单数字密码破解

import java.util.ArrayList;
import java.util.List;
public class PasswordBruteForce {
    // 破解4位数字密码
    public static String crack4DigitPassword(String targetPassword) {
        System.out.println("开始破解4位数字密码...");
        for (int i = 0; i <= 9999; i++) {
            String attempt = String.format("%04d", i);
            System.out.println("尝试密码: " + attempt);
            if (attempt.equals(targetPassword)) {
                System.out.println("破解成功!密码是: " + attempt);
                return attempt;
            }
        }
        System.out.println("破解失败");
        return null;
    }
    // 通用密码破解(指定字符集和长度)
    public static String crackPassword(String targetPassword, 
                                      String charset, 
                                      int maxLength) {
        System.out.println("开始暴力破解密码...");
        System.out.println("字符集: " + charset);
        System.out.println("最大长度: " + maxLength);
        for (int length = 1; length <= maxLength; length++) {
            String result = generateAndCheck(targetPassword, charset, 
                                           new StringBuilder(), length);
            if (result != null) {
                return result;
            }
        }
        return null;
    }
    private static String generateAndCheck(String target, String charset, 
                                          StringBuilder prefix, int remaining) {
        if (remaining == 0) {
            String attempt = prefix.toString();
            System.out.println("尝试: " + attempt);
            if (attempt.equals(target)) {
                return attempt;
            }
            return null;
        }
        for (int i = 0; i < charset.length(); i++) {
            prefix.append(charset.charAt(i));
            String result = generateAndCheck(target, charset, prefix, remaining - 1);
            prefix.deleteCharAt(prefix.length() - 1);
            if (result != null) {
                return result;
            }
        }
        return null;
    }
    public static void main(String[] args) {
        // 示例1:破解4位数字密码
        String password1 = "1234";
        crack4DigitPassword(password1);
        System.out.println("========================");
        // 示例2:破解2位小写字母密码
        String password2 = "ab";
        String charset = "abcdefghijklmnopqrstuvwxyz";
        String result = crackPassword(password2, charset, 2);
        if (result != null) {
            System.out.println("破解成功!密码是: " + result);
        } else {
            System.out.println("破解失败");
        }
    }
}

2 多线程暴力破解

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
public class MultiThreadBruteForce {
    private static final AtomicBoolean found = new AtomicBoolean(false);
    private static volatile String password = null;
    public static void multiThreadCrack(String targetPassword, 
                                       String charset, 
                                       int maxLength, 
                                       int threadCount) {
        System.out.println("多线程暴力破解开始...");
        System.out.println("线程数: " + threadCount);
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);
        int chunkSize = charset.length() / threadCount;
        for (int i = 0; i < threadCount; i++) {
            int start = i * chunkSize;
            int end = (i == threadCount - 1) ? charset.length() : (i + 1) * chunkSize;
            String subCharset = charset.substring(start, end);
            executor.submit(new CrackWorker(targetPassword, subCharset, maxLength, i));
        }
        executor.shutdown();
        while (!executor.isTerminated()) {
            // 等待所有线程完成
        }
        if (password != null) {
            System.out.println("破解成功!密码是: " + password);
        } else {
            System.out.println("破解失败");
        }
    }
    static class CrackWorker implements Runnable {
        private String targetPassword;
        private String charset;
        private int maxLength;
        private int workerId;
        public CrackWorker(String targetPassword, String charset, 
                          int maxLength, int workerId) {
            this.targetPassword = targetPassword;
            this.charset = charset;
            this.maxLength = maxLength;
            this.workerId = workerId;
        }
        @Override
        public void run() {
            System.out.println("工作线程 " + workerId + " 启动,字符集: " + charset);
            for (int length = 1; length <= maxLength && !found.get(); length++) {
                generateAndCheck(targetPassword, charset, new StringBuilder(), length);
            }
        }
        private void generateAndCheck(String target, String charset, 
                                     StringBuilder prefix, int remaining) {
            if (found.get()) return;
            if (remaining == 0) {
                String attempt = prefix.toString();
                if (attempt.equals(target)) {
                    password = attempt;
                    found.set(true);
                }
                return;
            }
            for (int i = 0; i < charset.length() && !found.get(); i++) {
                prefix.append(charset.charAt(i));
                generateAndCheck(target, charset, prefix, remaining - 1);
                prefix.deleteCharAt(prefix.length() - 1);
            }
        }
    }
    public static void main(String[] args) {
        String password = "xyz";
        String charset = "abcdefghijklmnopqrstuvwxyz";
        long startTime = System.currentTimeMillis();
        multiThreadCrack(password, charset, 3, 4);
        long endTime = System.currentTimeMillis();
        System.out.println("耗时: " + (endTime - startTime) + "ms");
    }
}

算法问题暴力求解

1 背包问题的暴力解法

import java.util.ArrayList;
import java.util.List;
public class KnapsackBruteForce {
    static class Item {
        String name;
        int weight;
        int value;
        public Item(String name, int weight, int value) {
            this.name = name;
            this.weight = weight;
            this.value = value;
        }
    }
    // 暴力求解0-1背包问题
    public static List<Item> knapsackBruteForce(List<Item> items, int capacity) {
        int n = items.size();
        int maxValue = 0;
        List<Item> bestCombination = new ArrayList<>();
        // 枚举所有可能的组合(2^n种)
        for (int i = 0; i < (1 << n); i++) {
            List<Item> currentCombination = new ArrayList<>();
            int currentWeight = 0;
            int currentValue = 0;
            // 检查当前组合
            for (int j = 0; j < n; j++) {
                if ((i & (1 << j)) != 0) {
                    currentCombination.add(items.get(j));
                    currentWeight += items.get(j).weight;
                    currentValue += items.get(j).value;
                }
            }
            // 如果当前组合更好且不超过容量
            if (currentWeight <= capacity && currentValue > maxValue) {
                maxValue = currentValue;
                bestCombination = new ArrayList<>(currentCombination);
            }
        }
        return bestCombination;
    }
    public static void main(String[] args) {
        List<Item> items = new ArrayList<>();
        items.add(new Item("物品A", 2, 3));
        items.add(new Item("物品B", 3, 4));
        items.add(new Item("物品C", 4, 5));
        items.add(new Item("物品D", 5, 8));
        int capacity = 8;
        System.out.println("背包容量: " + capacity);
        System.out.println("物品列表:");
        for (Item item : items) {
            System.out.println("  " + item.name + " (重量:" + item.weight + 
                             ", 价值:" + item.value + ")");
        }
        List<Item> bestCombination = knapsackBruteForce(items, capacity);
        System.out.println("\n最优组合:");
        int totalWeight = 0;
        int totalValue = 0;
        for (Item item : bestCombination) {
            System.out.println("  " + item.name);
            totalWeight += item.weight;
            totalValue += item.value;
        }
        System.out.println("总重量: " + totalWeight);
        System.out.println("总价值: " + totalValue);
    }
}

2 旅行商问题的暴力求解

import java.util.*;
public class TSPBruteForce {
    // 暴力求解旅行商问题
    public static class TSPResult {
        List<Integer> path;
        int minDistance;
        public TSPResult(List<Integer> path, int minDistance) {
            this.path = path;
            this.minDistance = minDistance;
        }
    }
    public static TSPResult solveTSP(int[][] distance) {
        int n = distance.length;
        List<Integer> cities = new ArrayList<>();
        for (int i = 1; i < n; i++) {
            cities.add(i);
        }
        int minDistance = Integer.MAX_VALUE;
        List<Integer> bestPath = new ArrayList<>();
        // 生成所有排列
        List<List<Integer>> permutations = new ArrayList<>();
        generatePermutations(cities, 0, permutations);
        // 计算每种排列的距离
        for (List<Integer> perm : permutations) {
            int currentDistance = 0;
            int currentCity = 0; // 从城市0开始
            for (int city : perm) {
                currentDistance += distance[currentCity][city];
                currentCity = city;
            }
            // 返回起点
            currentDistance += distance[currentCity][0];
            if (currentDistance < minDistance) {
                minDistance = currentDistance;
                bestPath = new ArrayList<>(perm);
            }
        }
        // 构建完整路径
        List<Integer> fullPath = new ArrayList<>();
        fullPath.add(0);
        fullPath.addAll(bestPath);
        fullPath.add(0);
        return new TSPResult(fullPath, minDistance);
    }
    private static void generatePermutations(List<Integer> arr, 
                                            int index, 
                                            List<List<Integer>> result) {
        if (index == arr.size() - 1) {
            result.add(new ArrayList<>(arr));
            return;
        }
        for (int i = index; i < arr.size(); i++) {
            Collections.swap(arr, i, index);
            generatePermutations(arr, index + 1, result);
            Collections.swap(arr, i, index);
        }
    }
    public static void main(String[] args) {
        // 城市间距离矩阵
        int[][] distance = {
            {0, 10, 15, 20},
            {10, 0, 35, 25},
            {15, 35, 0, 30},
            {20, 25, 30, 0}
        };
        System.out.println("城市距离矩阵:");
        for (int i = 0; i < distance.length; i++) {
            System.out.println(Arrays.toString(distance[i]));
        }
        TSPResult result = solveTSP(distance);
        System.out.println("\n最优路径: " + result.path);
        System.out.println("最短距离: " + result.minDistance);
        System.out.println("\n验证距离计算:");
        for (int i = 0; i < result.path.size() - 1; i++) {
            int from = result.path.get(i);
            int to = result.path.get(i + 1);
            System.out.println(from + " -> " + to + " : " + distance[from][to]);
        }
    }
}

实际应用示例:验证码破解

import java.util.Random;
public class CaptchaBruteForce {
    // 模拟的验证码验证函数
    public static boolean verifyCaptcha(String captcha) {
        // 假设验证码是 "ABC123"
        return captcha.equals("ABC123");
    }
    // 暴力破解4位字母数字验证码
    public static String crackCaptcha() {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        System.out.println("开始破解验证码...");
        System.out.println("字符集长度: " + chars.length());
        int attempts = 0;
        long startTime = System.currentTimeMillis();
        // 生成所有6位组合(3字母+3数字的简化版)
        for (int a = 0; a < 26; a++) {
            for (int b = 0; b < 26; b++) {
                for (int c = 0; c < 26; c++) {
                    for (int d = 0; d < 10; d++) {
                        for (int e = 0; e < 10; e++) {
                            for (int f = 0; f < 10; f++) {
                                String captcha = String.format("%c%c%c%d%d%d", 
                                    (char)('A' + a), 
                                    (char)('A' + b), 
                                    (char)('A' + c), 
                                    d, e, f);
                                attempts++;
                                if (verifyCaptcha(captcha)) {
                                    long endTime = System.currentTimeMillis();
                                    System.out.println("破解成功!");
                                    System.out.println("验证码: " + captcha);
                                    System.out.println("尝试次数: " + attempts);
                                    System.out.println("耗时: " + (endTime - startTime) + "ms");
                                    return captcha;
                                }
                                // 进度显示(每10万次)
                                if (attempts % 100000 == 0) {
                                    System.out.println("已尝试: " + attempts + " 次");
                                }
                            }
                        }
                    }
                }
            }
        }
        return null;
    }
    public static void main(String[] args) {
        String result = crackCaptcha();
        if (result == null) {
            System.out.println("破解失败");
        }
    }
}

优化技巧和注意事项

优化技巧:

public class BruteForceOptimization {
    // 1. 剪枝优化
    public static boolean earlyTermination(String target) {
        // 如果发现明显不符合条件,立即停止当前分支
        return false; // 示例返回
    }
    // 2. 启发式搜索
    public static List<String> heuristicSearch(String partial) {
        List<String> candidates = new ArrayList<>();
        // 根据部分信息缩小搜索范围
        // 如果知道密码包含特定字符
        return candidates;
    }
    // 3. 字典攻击(常见密码列表)
    public static String dictionaryAttack(String target) {
        String[] commonPasswords = {
            "password", "123456", "12345678", "qwerty", 
            "admin", "letmein", "welcome", "monkey"
        };
        for (String pwd : commonPasswords) {
            if (pwd.equals(target)) {
                return pwd;
            }
        }
        return null;
    }
}

注意事项:

  1. 合法性:只在授权系统上使用
  2. 性能考虑:暴力破解时间复杂度极高
  3. 内存管理:避免生成大量中间数据
  4. 超时机制:设置合理的超时时间

暴力破解是解决问题的最直接方法,但效率极低,实际应用中应该:

  • 优先使用更有效的算法(动态规划、回溯等)
  • 只在问题规模较小时使用暴力破解
  • 结合启发式方法提高效率
  • 注意合法合规使用

这些代码示例展示了Java在暴力破解问题中的典型应用,实际开发中要谨慎使用。

抱歉,评论功能暂时关闭!