views:

60

answers:

1

The following code prints randomly 634, 635, 636, each time I run it. Why its not constant?

public static void main(String[] args) throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", "BC");
    keyPairGen.initialize(1024);
    RsaKeyPair keyPair = new RsaKeyPair(keyPairGen.generateKeyPair());
    System.out.println(keyPair.getPrivate().getEncoded().length);
}
+4  A: 

As I explained in other threads, getEncoded() returns a DER-encoded ASN.1 object. In BER and DER encoding, the integers are encoded with variable number of octets. The main difference between DER and BER is that DER requires shortest encoding.

There are several primes in the RSAPrivateKey object and they may not take up the full 1024-bit and it will cause the size difference in DER encoding.

ZZ Coder