编程语言
首页 > 编程语言> > Java通过异或运算实现字符串解密

Java通过异或运算实现字符串解密

作者:互联网

public class MyStringUtils {

//    public static String encryptString(String target,Integer factor){
//        byte[] bytes = target.getBytes();
//        for (int i = 0; i < bytes.length; i++) {
//            bytes[i] ^= factor;
//        }
//
//        return new String(bytes);
//    }
//
//    public static String decodeString(String target, Integer factor){
//        byte[] bytes = target.getBytes();
//        for (int i = 0; i < bytes.length; i++) {
//            bytes[i] ^= factor;
//        }
//
//        return new String(bytes);
//    }

    public static String encryptString(String target,Integer factor){
        char[] chars = target.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            chars[i] ^= factor;
        }

        return new String(chars);
    }

    public static String decodeString(String target, Integer factor){
        char[] chars = target.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            chars[i] ^= factor;
        }

        return new String(chars);
    }

    public static void main(String[] args) {
        String target = "你好啊";
        int factor = 31;
        String encryptString = encryptString(target, factor);
        System.out.println("加密后的字符串为===="+encryptString);
        System.out.println("解密后的字符串为===="+decodeString(encryptString, factor));
    }
}

输出结果

加密后的字符串为====使奢啕
解密后的字符串为====你好啊

思考:

为什么我把字节数组那段给注释掉了

如果使用字节数组会出现什么问题

标签:encryptString,Java,target,chars,bytes,解密,异或,factor,String
来源: https://www.cnblogs.com/dtx123/p/16515254.html