Incorrect Type Conversion or Cast

ID

scala.strings.scala_strings_rule_badhexconversion

Severity

low

Remediation Complexity

medium

Remediation Risk

medium

Remediation Effort

medium

Resource

Strings

Language

Scala

Description

When converting a byte array containing a hash signature to a human readable string, a conversion mistake can be made if the array is read byte by byte.

Rationale

When converting a byte array containing a hash signature to a human readable string, a conversion mistake can be made if the array is read byte by byte.

The following code illustrates a vulnerable pattern detected by this rule:

// `toHexString` on a signed byte drops the leading zero of a value below 0x10 and sign-extends
// one above 0x7f, so the rendered digest is shorter than it should be and collides.
class DigestRenderer {
  @throws[NoSuchAlgorithmException]
  @throws[UnsupportedEncodingException]
  def renderWithAForComprehension(text: String) = {
    val digest: MessageDigest = MessageDigest.getInstance("SHA-256")
    // VULNERABLE: Incorrect Type Conversion or Cast
    val bytes = digest.digest(text.getBytes("UTF-8"))
    val rendered = new StringBuilder
    for (b <- bytes) {
      rendered.append(Integer.toHexString(b))
    }
    rendered.toString
  }

  @throws[NoSuchAlgorithmException]
  @throws[UnsupportedEncodingException]
}

Remediation

Follow secure coding practices and review the references below for detailed remediation guidance.

Configuration

This detector does not need any configuration.

References

© 2026 Xygeni. All rights reserved