How to generate fixed length string from another string

Viewed 58

Is it possible from one string (date) generate another fixed length string (5-char code) by some encrypting algorithm for example? Also should be possible to confirm that a output string (5-char code) has been generated using the input string (date)

What I need:

  • generateCode("10-10-2010") -> "HG45Q"
  • isCodeValid("HG45Q", "10-10-2010") -> true
2 Answers

Slightly hacky and not tested fully, but seems to do the job. I shall leave you to code the inverse function for validation:

public static String generateCode(String s) {
    String result = null;
    s = s.replaceAll("\\D", "");
    result = new BigInteger(s).toString(36).toUpperCase();
    while (result.length() < 5) {
        result = "0" + result;
    }
    return result;
}
class HelloWorld {
    public static void main(String[] args) {
        System.out.println(toHexString("10-10-2010".getBytes()));
        System.out.println();
        System.out.println(fromHexString("31302d31302d32303130"));

    }
    public static String toHexString(byte[] ba) {
    StringBuilder str = new StringBuilder();
    for(int i = 0; i < ba.length; i++)
        str.append(String.format("%x", ba[i]));
    return str.toString();
}

public static String fromHexString(String hex) {
    StringBuilder str = new StringBuilder();
    for (int i = 0; i < hex.length(); i+=2) {
        str.append((char) Integer.parseInt(hex.substring(i, i + 2), 16));
    }
    return str.toString();
}
}
Related