Java || Fixed Length Random Code Generator
We are going to learn how to generate a fixed length random string code in Java.
Problem Statement: We need to generate fixed length unique randomcode based of customerId and customerAccountId.
Acceptance: Genearted random code will always be same for particular given customerId and customerAccountId
Java Code:
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class GenerateRandomCodeUtills {
private static final Logger log = LogManager.getLogger(GenerateRandomCodeUtills.class);
@Value(“${randomcode.maxlength}”)
private int maxlength;
public String getRandomCode(String customerId, Integer customerAccountId) {
log.trace(“ENTER : getRandomCode() with customerId and customerAccountId”);
StringBuilder sb = new StringBuilder();
sb.append(customerId);
sb.append(customerAccountId);
log.trace(“customerId {} and customerAccountId {}”,customerId,customerAccountId);
String randomCode = “”;
try {
randomCode = toHexString(getSHA(sb.toString())).substring(0, maxlength).toUpperCase();
} catch (NoSuchAlgorithmException e) {
log.error(“Exception thrown for incorrect algorithm:{} “, e.getMessage());
}
log.trace(“randomCode {}”,randomCode);
return randomCode;
}
public static byte[] getSHA(String input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(“SHA-512”);
return md.digest(input.getBytes(StandardCharsets.UTF_8));
}
public static String toHexString(byte[] hash) {
BigInteger number = new BigInteger(1, hash);
StringBuilder hexString = new StringBuilder(number.toString(16));
while (hexString.length() < 32) {
hexString.insert(0, ‘0’);
}
return hexString.toString();
}
}