如何在Java中使用密钥库来存储私钥?

我曾经KeyPairGenerator生成过RSA密钥对。如果我没看错,那么KeyStore仅用于存储证书,而不用于存储密钥。如何将私钥正确存储在计算机上?

回答:

注意:此代码仅用于演示目的。将私钥存储在磁盘上时,必须对其进行加密。不要按原样使用它。

您可以执行以下操作:

 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");

kpg.initialize(2048);

KeyPair kp = kpg.genKeyPair();

KeyFactory fact = KeyFactory.getInstance("RSA");

RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),

RSAPublicKeySpec.class);

saveToFile(PUBLIC_KEY_FILE,

pub.getModulus(), pub.getPublicExponent());

RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(),

RSAPrivateKeySpec.class);

saveToFile(PRIVATE_KEY_FILE,

priv.getModulus(), priv.getPrivateExponent());

保存功能:

private static void saveToFile(String fileName,

BigInteger mod, BigInteger exp)

throws SomeException {

ObjectOutputStream oout = new ObjectOutputStream(

new BufferedOutputStream(new FileOutputStream(fileName)));

try {

oout.writeObject(mod);

oout.writeObject(exp);

} catch (Exception e) {

throw new SomeException(e);

} finally {

oout.close();

}

}

并以相同的方式读回:

private static PublicKey readPublicKey() throws SomeException {

InputStream in = new FileInputStream(PUBLIC_KEY_FILE);

ObjectInputStream oin =

new ObjectInputStream(new BufferedInputStream(in));

try {

BigInteger m = (BigInteger) oin.readObject();

BigInteger e = (BigInteger) oin.readObject();

RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);

KeyFactory fact = KeyFactory.getInstance("RSA");

PublicKey pubKey = fact.generatePublic(keySpec);

return pubKey;

} catch (Exception e) {

throw new SomeException(e);

} finally {

oin.close();

}

}

读取私钥相似。

以上是 如何在Java中使用密钥库来存储私钥? 的全部内容, 来源链接: utcz.com/qa/427531.html

回到顶部