PublicKey vs RSAPublicKeySpec

When I create an RSA key pair, I have to do

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?

+3
source share
2 answers

For public keys, this is not a big deal. For private keys, getEncoded () returns much more information than a private key.

Here is the ASN.1 schema for the 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
}

These additional parameters will significantly speed up the operation of the private key. Therefore, you should always use getEncoded().

+4
source

getEncoded() , " " , , , . , PKCS # 1.

, , , KeyStore java .

0

Source: https://habr.com/ru/post/1752970/


All Articles