温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java中xor如何实现加密

发布时间:2026-10-08 09:47:20 来源:亿速云 阅读:100 作者:小樊 栏目:编程语言

在 Java 中,XOR(异或)加密是一种非常简单且常见的对称加密方式,核心原理是利用 异或运算的可逆性:

A ^ B = C
C ^ B = A

也就是说,用同一个“密钥”对数据进行异或,可以加密;再异或一次,就可以解密。


一、XOR 运算基础

Java 中的异或运算符是 ^:

int a = 5;   // 0101
int b = 3;   // 0011
int c = a ^ b; // 0110 = 6
int d = c ^ b; // 0101 = 5

二、使用 XOR 对字符串加密(单字节密钥)

示例:用固定密钥加密字符串

public class XorEncrypt {

    // 加密和解密使用同一个方法
    public static String xorString(String text, char key) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            result.append((char)(text.charAt(i) ^ key));
        }
        return result.toString();
    }

    public static void main(String[] args) {
        String original = "HelloWorld";
        char key = 'K';

        String encrypted = xorString(original, key);
        System.out.println("加密后: " + encrypted);

        String decrypted = xorString(encrypted, key);
        System.out.println("解密后: " + decrypted);
    }
}

⚠️ 注意:加密后的字符串可能包含不可见字符,直接打印可能显示异常。


三、使用 XOR 对字节数组加密(更通用)

常用于文件、网络数据加密:

public class XorUtil {

    public static byte[] xor(byte[] data, byte key) {
        byte[] result = new byte[data.length];
        for (int i = 0; i < data.length; i++) {
            result[i] = (byte) (data[i] ^ key);
        }
        return result;
    }

    public static void main(String[] args) {
        byte[] data = "Hello".getBytes();
        byte key = 0x5A;

        byte[] encrypted = xor(data, key);
        byte[] decrypted = xor(encrypted, key);

        System.out.println(new String(decrypted));
    }
}

四、使用“密钥流”增强安全性(多字节密钥)

public static byte[] xorWithKey(byte[] data, byte[] key) {
    byte[] result = new byte[data.length];
    for (int i = 0; i < data.length; i++) {
        result[i] = (byte) (data[i] ^ key[i % key.length]);
    }
    return result;
}

这种方式类似 流密码(Stream Cipher)。


五、XOR 加密的特点

✅ 优点

  • 实现简单
  • 性能极高
  • 加密解密同一算法

❌ 缺点(重要)

  • 安全性极低
  • 密钥短 → 容易被破解
  • 不适合真实业务加密

六、实际开发建议

✅ 学习 / 演示 / 简单混淆:可以用 XOR
❌ 真实加密需求:请使用 Java 标准加密库

// 推荐
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

如果你愿意,我可以:

  • 帮你写一个 XOR 文件加密工具
  • 对比 XOR vs AES
  • 写一个 Base64 + XOR 的示例

你想用 XOR 做什么场景?

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手