Usage of bad hex conversion on digest array

Description

Your application is using Integer.toHexString for converting a digest array buffer into a hexadecimal string, which may lead to incorrect representations.

Remediations

  • Do not use Integer.toHexString for converting digest arrays to hexadecimal strings due to the risk of inaccuracies.
    String hexString = Integer.toHexString(byteValue); // unsafe
  • Do use java.util.HexFormat for accurate hexadecimal conversion in Java 17 and above.
    MessageDigest sha256Digest = MessageDigest.getInstance("SHA-256");
    sha256Digest.update("hello world".getBytes(StandardCharsets.UTF_8));
    byte[] output = sha256Digest.digest();

    HexFormat hex = HexFormat.of();
    String hexString = hex.formatHex(output);
  • Do consider using javax.xml.bind.DatatypeConverter.printHexBinary for Java versions prior to 17 as an alternative for accurate hex conversion.

References

Associated CWE

Configuration

To skip this rule during a scan, use the following flag

bearer scan /path/to/your-project/ --skip-rule=java_lang_bad_hex_conversion

To run only this rule during a scan, use the following flag

bearer scan /path/to/your-project/ --only-rule=java_lang_bad_hex_conversion