3

当我创建一个 RSA 密钥对时,我应该做什么

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())

或者

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());

哪个更好,有什么区别?

4

2 回答 2

4

对于公钥,它没有太大区别。对于私钥,getEncoded() 返回的信息比私钥多得多。

这是 RSA 私钥的 ASN.1 模式,

-- 
-- 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
}

这些额外的参数将大大加快私钥操作。因此,您应该始终使用getEncoded().

于 2010-07-03T14:25:13.340 回答
0

getEncoded() 方法返回“更多”标准的公钥和私钥编码,因此更可能与其他系统互操作。也就是说,它们使用诸如 PKCS#1 之类的标准。

如果您不关心互操作性,那么您可能应该使用 java KeyStore 类来存储密钥。

于 2010-07-03T14:10:30.283 回答