一个简单的字符串加解密

public class MyTest {
    public static void main(String[] args) {

        String out = encode("https://www.baidu.com?code=1028".getBytes(StandardCharsets.UTF_8));
        System.out.println(out);
        System.out.println(new String(decode(out)));
    }

    public static String encode(byte[] binaryData) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : binaryData) {
            hexString.append(String.format("%02X", b)); // 使用"%02X"将字节转换为两位的十六进制字符串
        }
        return hexString.toString();
    }

    // 步骤1:将十六进制字符串转换为二进制数据
    public static byte[] decode(String hexString) {
        if (hexString.length() % 2 != 0) {
            throw new IllegalArgumentException("Invalid hex string");
        }
        int length = hexString.length() / 2;
        byte[] binaryData = new byte[length];
        for (int i = 0; i < length; i++) {
            int index = i * 2;
            int high = Character.digit(hexString.charAt(index), 16);
            int low = Character.digit(hexString.charAt(index + 1), 16);
            if (high < 0 || low < 0) {
                throw new IllegalArgumentException("Invalid hex string");
            }
            binaryData[i] = (byte) ((high << 4) + low);
        }
        return binaryData;
    }
}

你可能感兴趣的:(字符串加密)