---
title: Bad hexadecimal concatenation
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Datadog Security > Code Security > Static Code Analysis (SAST) > SAST
  Rules > Bad hexadecimal concatenation
---

# Bad hexadecimal concatenation

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com

{% alert level="danger" %}
This product is not supported for your selected [Datadog site](https://docs.datadoghq.com/getting_started/site.md). ().
{% /alert %}

{% /callout %}

## Metadata{% #metadata %}

**ID:** `java-security/bad-hexa-concatenation`

**Language:** Java

**Severity:** Warning

**Category:** Security

**CWE**: [704](https://cwe.mitre.org/data/definitions/704.html)

**Related CWEs**:

- [681](https://cwe.mitre.org/data/definitions/681.html)
- [843](https://cwe.mitre.org/data/definitions/843.html)
- [1389](https://cwe.mitre.org/data/definitions/1389.html)

## Description{% #description %}

This rule detects improper concatenation of hexadecimal strings generated by methods like `Integer.toHexString()` without ensuring a fixed length for each byte representation. Such concatenation can produce inconsistent or ambiguous results because `toHexString()` omits leading zeros, causing the output to vary in length and potentially misrepresent the intended data.

To ensure you get a consistent hexadecimal representation get the hexadecimal representation of a value using `String.format("%02x", b)` or `String.format("%02X", b)`. This guarantees consistent length and proper zero-padding for each byte.

## Non-Compliant Code Examples{% #non-compliant-code-examples %}

```java
class Compliant2 {
  public static String getBitfieldHex(final int bitfield) {
    String hex = Integer.toHexString(bitfield & 0xFF);
  }

  public static String getBitfieldHex2() {
    int bitfield = 1;
    String hex = Integer.toHexString(foo & 0xFF);
  }
}
```

```java
class NotCompliant {
    public void myMethod() {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] resultBytes = md.digest(password.getBytes("UTF-8"));

        StringBuilder stringBuilder = new StringBuilder();
        for(byte b :resultBytes) {
            stringBuilder.append(Integer.toHexString( b & 0xFF ));
        }

        return stringBuilder.toString();
    }
}
```

## Compliant Code Examples{% #compliant-code-examples %}

```java
class NotCompliant {
    public void myMethod() {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] resultBytes = md.digest(password.getBytes("UTF-8"));

        StringBuilder stringBuilder = new StringBuilder();
        for(byte b :resultBytes) {
            stringBuilder.append( String.format( "%02X", b ) );
        }

        return stringBuilder.toString();
    }
}
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 