| name | secure-message-digest-generation |
| description | Generate secure message digest (often called hash) generation code. Enforces secure generation of a message digest. Invoke when writing any message digest generation related code. |
| allowed-tools | Read Grep Glob |
| metadata | {"category":"security"} |
Secure Message Digest Code Generation Rules
Apply all rules below when generating or reviewing any code related to message digest generation.
1. Secure algorithm usage and hash collision prevention (CRITICAL)
- ALWAYS ensure that the hashing algorithm used is the strongest that exists, from a cryptography perspective, at the moment at which the code is generated. In case of any doubt always use
SHA3-512 algorithm.
- ALWAYS ensure that the hashing algorithm used is post-quantum resistant.
- ALWAYS ensure that each value used to create the digest is explicitly separated by the character
| (appended after every value, even when only one value is provided) prior to the final concatenated value being provided to the hashing function.
- ALWAYS encode the input string to bytes using the
UTF-8 charset explicitly — never rely on the platform default charset, as it may vary across environments and produce different digests for the same input.
- ALWAYS convert null or empty values to an explicit empty string
"" before including them in the digest input — never skip or silently drop them, as omitting a value changes the digest in the same way a different value would.
- ALWAYS encode the raw digest bytes as a lowercase hexadecimal string — never return raw bytes or use Base64, as hex is the canonical, human-readable, and interoperable representation for message digests.
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
public byte[] computeDigestInsecure(Object[] values) throws NoSuchAlgorithmException {
StringBuilder combined = new StringBuilder();
for (Object value : values) {
combined.append(value != null ? value.toString() : "");
}
MessageDigest md = MessageDigest.getInstance("SHA1");
byte[] hashBytes = md.digest(combined.toString().getBytes());
return hashBytes;
}
public String computeDigestSecure(Object[] values) throws NoSuchAlgorithmException {
StringBuilder combined = new StringBuilder();
for (Object value : values) {
combined.append((value == null || value.toString().isEmpty()) ? "" : value.toString());
combined.append("|");
}
MessageDigest md = MessageDigest.getInstance("SHA3-512");
byte[] hashBytes = md.digest(combined.toString().getBytes(StandardCharsets.UTF_8));
String hexDigest = HexFormat.of().formatHex(hashBytes);
return hexDigest;
}
2. Output Checklist
Before finalizing generated code, verify:
References