XOR operation with two strings in java

前端 未结 7 551
有刺的猬
有刺的猬 2020-11-28 05:48

How to do bitwise XOR operation to two strings in java.

7条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 06:26

    You want something like this:

    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", "");
    
        }
    }
    

    The base64 encoding is done because xor'ing the bytes of a string may not give valid bytes back for a string.

提交回复
热议问题