Simple algorithm for mixing/obfuscating a string with pre-defined chars

后端 未结 5 641
北恋
北恋 2021-01-31 05:39

I have a string as follows:

  • Its length is 10.
  • It represents base 36 and as such includes digits and uppercase letters.
  • The origin of the st
5条回答
  •  旧时难觅i
    2021-01-31 06:13

    This is a generic solution, this a very fast algorithm that can handle any string in any encoding.

    Source code

    public class Translator {
    
        private static final String key = "Zx" + Math.log(2) / 3;
    
        public static String obfuscate(String s) {
            char[] result = new char[s.length()];
            for (int i = 0; i < s.length(); i++) {
                result[i] = (char) (s.charAt(i) + key.charAt(i % key.length()));
            }
    
            return new String(result);
        }
    
        public static String unobfuscate(String s) {
            char[] result = new char[s.length()];
            for (int i = 0; i < s.length(); i++) {
                result[i] = (char) (s.charAt(i) - key.charAt(i % key.length()));
            }
    
            return new String(result);
        }
    }
    

    Usage

    String obfuscate = Translator.obfuscate("Hi there");
    System.out.println(obfuscate + " - " + Translator.unobfuscate(obfuscate));
    

    Output:

    ¢áP¢£ - Hi there
    

提交回复
热议问题