Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Major change to the first NCCE plus some rewording and a new Bibliography entry

...

The following code example demonstrates such an attack:

Code Block
bgColor#FFCCCC
BigInteger msg = new BigInteger("123");
msg = msg.modPow(exp, m);  // Always returns 1

// Malicious subclassing of java.math.BigInteger
class BigInteger extends java.math.BigInteger {
  private intbyte[] valueba;

  public BigInteger(String str) {
    super(str);
    valueba = Integer.parseInt(str (new java.math.BigInteger(str)).toByteArray();
  }

  public void setValue(int valueBigInteger(byte[] ba) {
    super(ba);
    this.valueba = valueba;
  }

  public @Override public java.math.BigInteger modPow(
      java.math.BigInteger exponent, java.math.BigInteger mvoid setValue(byte[] ba) {
    this.valueba = ((int) (Math.pow(this.doubleValue(),  ba;
  }

  @Override public                               exponent.doubleValue()))) % m.intValue();byte[] toByteArray() {
    return thisba;
   }
}

Unlike the benign BigInteger class, this malicious BigInteger class is clearly mutable because of the setValue() method. Furthermore, the malicious modPow() method (which overrides a benign modPow() method) is subject to precision loss (see NUM00-J. Detect or prevent integer overflow, NUM08-J. Check floating-point inputs for exceptional values, NUM12-J. Ensure conversions of numeric types to narrower types do not result in lost or misinterpreted data, and NUM13-J. Avoid loss of precision when converting primitive integers to floating-point for more information). Any code that receives an object of this class and assumes that the object is immutable will behave unexpectedly, as shown by the following code:

Code Block
bgColor#FFCCCC
BigInteger bi = new BigInteger("123");

bi.setValue((new BigInteger("246")).toByteArray());

System.out.println(new BigInteger(bi.toByteArray()));  

This code prints: "246", which shows that the value of the supposedly immutable BigInteger bi has been changed.

This example is particularly important because the BigInteger.modPow() method type has several useful cryptographic applications.

...

[API 2006]

Class BigInteger

[Bloch 2008]

Item 15: "Minimize mutability"

Item 17, "Design and Document for Inheritance or Else Prohibit It"

[Gong 2003]

Chapter 6, "Enforcing Security Policy"

[Lai 2008]

Java Insecurity, Accounting for Subtleties That Can Compromise Code

[McGraw 1999]

Chapter 7, Rule 3, Make everything final, unless there's a good reason not to

[SCG 2009] 
[Ware 2008] 

...