gpt4 book ai didi

java - java中两个字符串的异或运算

转载 作者:IT老高 更新时间:2023-10-28 20:31:05 28 4
gpt4 key购买 nike

如何在java中对两个字符串进行按位异或运算。

最佳答案

你想要这样的东西:

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.IOException;

public class StringXORer {

public String encode(String s, String key) {
return base64Encode(xorWithKey(s.getBytes(), key.getBytes()));
}

public String decode(String s, String key) {
return new String(xorWithKey(base64Decode(s), key.getBytes()));
}

private byte[] xorWithKey(byte[] a, byte[] key) {
byte[] out = new byte[a.length];
for (int i = 0; i < a.length; i++) {
out[i] = (byte) (a[i] ^ key[i%key.length]);
}
return out;
}

private byte[] base64Decode(String s) {
try {
BASE64Decoder d = new BASE64Decoder();
return d.decodeBuffer(s);
} catch (IOException e) {throw new RuntimeException(e);}
}

private String base64Encode(byte[] bytes) {
BASE64Encoder enc = new BASE64Encoder();
return enc.encode(bytes).replaceAll("\\s", "");

}
}

base64 编码已完成,因为对字符串的字节进行异或可能无法返回字符串的有效字节。

关于java - java中两个字符串的异或运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5126616/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com