# 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)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.sec1.io/user-docs/4-sast/2-java/usage-of-bad-hex-conversion-on-digest-array.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
