Description
Casting an int multiplication result to long widens a value that may already have overflowed during multiplication. A shift at or beyond the type’s bit width can also produce an unexpected result because of Java’s shift-distance rules. This is a calculation-correctness problem; its security impact depends on whether the result controls size limits, access decisions or similar behavior.
Potential impact
- Incorrect size, count or index calculations
- Unexpected bit masks and flags
- Incorrect intermediate results affecting later operations
Remediation
- Cast one operand to
longbefore multiplying. - Use
Math.multiplyExactif overflow must be reported as an error. - Check that a shift distance is smaller than the target type’s bit width.
- If a wider result is needed, widen the value before shifting.
Examples
Widening multiplication
Before
java
public long calculateSize(int itemCount, int itemSize) {
return (long) (itemCount * itemSize);
}
After
java
public long calculateSize(int itemCount, int itemSize) {
return (long) itemCount * itemSize;
}
Explanation:
- Before: The
intmultiplication happens before the cast and may already have overflowed. - After: Casting an operand first makes the multiplication use the
longrange.
Shift operations
Before
java
public int buildMask(int flags) {
return flags << 32;
}
After
java
public long buildMask(int flags) {
return ((long) flags) << 32;
}
Explanation:
- Before: Java uses only the low five bits of an
intshift distance, so shifting by32does not have the intended effect. - After: Widening to
longfirst makes this a 64-bit operation.