Do not use a predictable salt in cryptographic operations. Salts are meant to add randomness to data, making it harder for attackers to guess the input even if they know the hash. If the salt is predictable, such as a hard-coded string or a fixed byte array, it defeats the purpose of adding randomness and makes the data more vulnerable to attacks.
It’s also important to use a sufficiently large salt. A small salt size such as 8 bytes doesn’t provide enough randomness and can be easily brute-forced by attackers. The recommended salt size is a minimum of 16 bytes, and 32 bytes or more is ideal.
To comply with this rule, always generate a secure random salt using SecureRandom or SecureRandom.getInstanceStrong(). Fill a byte array of at least 16 bytes with this random salt, and use this array in the PBEParameterSpec. This ensures that the salt is unpredictable and large enough to provide sufficient randomness.
Non-Compliant Code Examples
// Hardcoded string salt
valsalt1="somesalt".toByteArray()valspec1=PBEParameterSpec(salt1,10000)// Fixed byte array salt
valsalt2=ByteArray(16).apply{fill(1)}valspec2=PBEParameterSpec(salt2,10000)// Small salt size
valrandom=SecureRandom()valsalt3=ByteArray(8)// Too small
random.nextBytes(salt3)valspec3=PBEParameterSpec(salt3,10000)
Compliant Code Examples
// Generate secure random salt
valrandom=SecureRandom()valsalt=ByteArray(32)// At least 32 bytes
random.nextBytes(salt)valspec=PBEParameterSpec(salt,10000)// Alternative using .getInstanceStrong()
valrandom=SecureRandom.getInstanceStrong()valsalt=ByteArray(32)random.nextBytes(salt)valspec=PBEParameterSpec(salt,10000)
Seamless integrations. Try Datadog Code Security
Datadog Code Security
Try this rule and analyze your code with Datadog Code Security
How to use this rule
1
2
rulesets:- kotlin-security # Rules to enforce Kotlin security.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Security scans to your CI pipelines