licel / jcardsim

https://jcardsim.org
224 stars 123 forks source link

OutOfBound exception or incorrect value in RSA private key component #89

Open petrs opened 8 years ago

petrs commented 8 years ago

Problem: components of RSA key (possibly also other algorithms) keeps its initial length of buffer allocated with the first call (e.g., via keyPair.genKeyPair();) Subsequent changes in size of components via setters will not change initial length => either is buffer too small (exception) or additional bytes(s) will be present (resulting in incorrect key value and subsequent fail during key usage)

EDIT: version used: jcardsim-2.2.2-all.jar

Code fragment to replicate issue:

KeyPair keyPair = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_1024);
byte[] buffer = new byte[128];
short DP1Len = 64;
RSAPrivateCrtKey privateKey = null;
while (DP1Len <= 64) {
    keyPair.genKeyPair();
    privateKey = (RSAPrivateCrtKey) keyPair.getPrivate();
    DP1Len = privateKey.getDP1(buffer, (short) 0);
}
// Now we have key with DP1 length longer than 64B
// Set 64B into DP1 => subsequent length after getDP1 should be 64
privateKey.setDP1(buffer, (short) 0, (short) 64);
assert(privateKey.getDP1(buffer, (short) 0) == 64); // fails (will be > 64B)
// If previous length of DP1 was 63, then setDP1(64) will fail writing outside dp1.data buffer

// Same issue when clear key was used 
privateKey.clearKey();
privateKey.setDP1(buffer, (short) 0, (short) 64);
assert(privateKey.getDP1(buffer, (short) 0) == 64); // fails (will be > 64B)