我用过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();
}
}
读取私钥也是类似的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)