java保存私钥_如何在Java中使用密钥库来存储私钥?
小編典典
注意:此代碼僅用于演示目的。將私鑰存儲在磁盤上時,必須對其進行加密。不要按原樣使用它。
您可以執(zhí)行以下操作:
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();
}
}
讀取私鑰相似。
2020-09-11
總結
以上是生活随笔為你收集整理的java保存私钥_如何在Java中使用密钥库来存储私钥?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java ftl 标签_Freemark
- 下一篇: java简单小程序_Java简易登录注册