views:

29

answers:

2

When I create an RSA keypair should I be be doing

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.genKeyPair();
PublicKey publicKey = kp.getPublic();
PrivateKey privateKey = kp.getPrivate();

save("public.key",publicKey.getEncoded())
save("private.key",privateKey.getEncoded())

OR

KeyFactory fact = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),RSAPublicKeySpec.class);
RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(),RSAPrivateKeySpec.class);

saveToFile("public.key", pub.getModulus(),pub.getPublicExponent());
saveToFile("private.key", priv.getModulus(),priv.getPrivateExponent());

Which is better and what is the difference?

A: 

The getEncoded() methods return encodings for public and private keys that are "more" standard and thus more likely to be interoperable with other systems. That is, they use standards such as PKCS#1.

If you are not concerned about interoperability then you should probably use the java KeyStore class for storing keys.

GregS
+1  A: 

For public keys, it doesn't make much difference. For private keys, getEncoded() returns much more information than the private key.

Here is the ASN.1 schema for RSA Private Key,

-- 
-- Representation of RSA private key with information for the CRT algorithm.
--
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 
}

Version ::= INTEGER { two-prime(0), multi(1) }
    (CONSTRAINED BY {-- version must be multi if otherPrimeInfos present --})

OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo


OtherPrimeInfo ::= SEQUENCE {
    prime             INTEGER,  -- ri
    exponent          INTEGER,  -- di
    coefficient       INTEGER   -- ti
}

Those extra parameters will speed up private key operations considerably. So you should always use getEncoded().

ZZ Coder
Hi, I have a small doubt. I have modulus and exponent. I need to create PublicKey. can you please let me know how to create "PublicKey" out of given 'modulus' and 'exponent'.
Andhravaala