Incorrect Type Conversion High

Failure to properly transform an object, resource, or structure from one type to a safer one.

Detector ID
kotlin/incorrect-type-conversion@v1.0
Category
Common Weakness Enumeration (CWE) external icon
Tags
-

Noncompliant example

1// Noncompliant: Using `Integer.toHexString()` which creates a weak hash
2fun noncompliant(password: String): String {
3    val md: MessageDigest = MessageDigest.getInstance("SHA-1")
4    val resultBytes: Array<Byte> = md.digest(password.getBytes("UTF-8"))
5
6    var stringBuilder: StringBuilder = StringBuilder()
7    for (b in resultBytes) {
8        stringBuilder.append(Integer.toHexString(b and 0xFF))
9    }
10
11    return stringBuilder.toString()
12}

Compliant example

1// Compliant: Using `String.format(\"%02X\",...)` which does not creates a weak hash
2fun compliant(password: String): String {
3    val md: MessageDigest = MessageDigest.getInstance("SHA-1")
4    val resultBytes: Array<Byte> = md.digest(password.getBytes("UTF-8"))
5
6    var stringBuilder: StringBuilder = StringBuilder()
7    for (b in resultBytes) {
8        stringBuilder.append(String.format("%02X", b))
9    }
10
11    return stringBuilder.toString()
12}