I've implemented a QR code generation logic in Java using the SHA-256 hash of input data, but I'm encountering a problem where I get the same QR code for different inputs. I've shared my code below:
private byte[] generateQRCode(String data, int number) {
try {
if (data == null) data = "";
if (number <= 0) number = 1;
// Hash the input data using SHA-256
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(data.getBytes());
// Encode the hash to Base64 to generate the QR code
String encodedHash = Base64.getEncoder().encodeToString(hash);
// Configure QR code hints
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(encodedHash, BarcodeFormat.QR_CODE, 200, 200, hints);
// Write the QR code bit matrix to a byte array
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
return outputStream.toByteArray();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error generating QR code bytes");
}
I'm using the SHA-256 hash of the input data as the basis for generating the QR code, and then encoding it to Base64. However, despite different inputs, the generated QR codes are identical. Can anyone help me identify the issue in my code or suggest a solution to ensure unique QR codes for different inputs?
What I Tried:
Debugging: Checked values at each step but found no differences between inputs. Tested with Varied Inputs: Tried different data types and lengths, yet QR codes remained identical. Reviewed Documentation: Examined libraries used but found no relevant issues.
Expectations:
Expected unique QR codes from different input hashes via SHA-256. Assumed distinct inputs would yield distinct QR codes. However, identical QR codes persist despite varying inputs. Seeking insights on potential flaws or missed details causing this issue.