本文介绍了在java中使用两个字符串进行XOR操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何对java中的两个字符串执行按位XOR运算。
How to do bitwise XOR operation to two strings in 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编码完成是因为xor '字符串的字节可能不会为字符串返回有效字节。
The base64 encoding is done because xor'ing the bytes of a string may not give valid bytes back for a string.
这篇关于在java中使用两个字符串进行XOR操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!