# Usage of bad hex conversion on digest array

## Overview

* **Rule ID**: `java_lang_bad_hex_conversion`
* **Applicable Languages**: Java
* **Weakness ID**: CWE-704

## Description

Your application uses `Integer.toHexString` to convert a digest array buffer into a hexadecimal string, potentially leading to incorrect representations.

## Risks

* Using `Integer.toHexString` for converting a digest array buffer to a hexadecimal string can result in incorrect formatting or data loss, leading to potential security vulnerabilities. This misrepresentation may compromise data integrity and affect cryptographic functions relying on accurate digest values.

## Remediation Guidelines

* **Do not** use `Integer.toHexString` for converting digest arrays to hexadecimal strings due to the risk of inaccuracies.

  ```java
  String hexString = Integer.toHexString(byteValue); // unsafe

  ```
* **Instead, use** `java.util.HexFormat` for accurate hexadecimal conversion in Java 17 and above:

  ```java
  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);

  ```
* **For Java versions prior to 17, consider using** `javax.xml.bind.DatatypeConverter.printHexBinary` as an alternative for accurate hex conversion.

## References

* [**DatatypeConverter**](https://docs.oracle.com/javase/9/docs/api/javax/xml/bind/DatatypeConverter.html#printHexBinary-byte:A-)
* [**CWE-704: Incorrect Type Conversion or Cast**](https://cwe.mitre.org/data/definitions/704.html)

## Configuration

To omit this rule during a scan, and to provide you with continuous 24/7 code-level scanning, you can employ our [**SAST TOOL**](https://scopy.sec1.io/login)
