views:

267

answers:

2

The key generator was initilized with a size of 1024, so why the printed sizes are 635 and 162?

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

public class TEST {

    public static KeyPair generateKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
    keyPairGenerator.initialize(1024);
    return keyPairGenerator.generateKeyPair();
    }

    public static void main(String[] args) throws Exception {

    KeyPair keyPair = generateKeyPair();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

    System.out.println("Size = " + privateKey.getEncoded().length);
    System.out.println("Size = " + publicKey.getEncoded().length);

    }

}
+1  A: 

First hint: 1024 bits = 128 bytes

Second hint: privateKey.getEncoded() returns an encoded representation (i.e. not raw).

leonbloy
thanks for hint 2, so how do I get the raw?
Tom Brito
The "key size" means different things for different coders, and is not trivially related to the key. In the case of RSA it's the size of the modulus. (You should use getModulus() ) See ZZ Coder's answer.
leonbloy
there's something wrong, the getModulus return a number of 309 digits. If this means the size is 309, its still not what a had setted (1024).
Tom Brito
digits are not bits
leonbloy
third hint : 1024 * Log10(2) = 308.25 => 1024 bits ~ 309 decimal digits
leonbloy
why Log10(2)?..
Tom Brito
leonbloy
+4  A: 

RSA keys are made of Modulus and Exponent. The key size refers to the bits in modulus. So even without any encoding overhead, you will need more than 128 bytes to store 1024-bit keys.

getEncoded() returns ASN.1 DER encoded objects. The private key even contains CRT parameters so it's very large.

To get key size, do something like this,

   System.out.println("Key size = " + publicKey.getModulus().bitLength());

Here are the relevant ASN.1 objects,

  RSAPrivateKey ::= SEQUENCE {
      version           Version,
      modulus           INTEGER,  -- n
      publicExponent    INTEGER,  -- e
      privateExponent   INTEGER,  -- d
      prime1            INTEGER,  -- p
      prime2            INTEGER,  -- q
      exponent1         INTEGER,  -- d mod (p-1)
      exponent2         INTEGER,  -- d mod (q-1)
      coefficient       INTEGER,  -- (inverse of q) mod p
      otherPrimeInfos   OtherPrimeInfos OPTIONAL
  }


  RSAPublicKey ::= SEQUENCE {
      modulus           INTEGER,  -- n
      publicExponent    INTEGER   -- e
  }
ZZ Coder
so, how do I check its size in the example code?
Tom Brito
See my edits ......
ZZ Coder