使用公共和私有JKS文件生成KeyPair

时间:2017-01-18 12:33:43

标签: java keystore key-pair

是否可以使用已生成的公钥和私钥库(JKS)文件在我的应用程序中生成KeyPair

由于

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair keypair = keyGen.genKeyPair();

我想创建已生成RSA 2048私钥和公钥的密钥对

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

public static KeyPair loadKeyStore(final File keystoreFile,
        final String password, final String alias, final String keyStoreType)
        throws Exception {
    if (null == keystoreFile) {
        throw new IllegalArgumentException("Keystore url may not be null");
    }
    final KeyStore keystore = KeyStore.getInstance(keyStoreType);
    InputStream is = null;
    try {
        is = new FileInputStream(keystoreFile);
        keystore.load(is, null == password ? null : password.toCharArray());
    } finally {
        if (null != is) {
            is.close();
        }
    }
    final PrivateKey key = (PrivateKey) keystore.getKey(alias,
            password.toCharArray());
    final Certificate cert = keystore.getCertificate(alias);
    final PublicKey publicKey = cert.getPublicKey();
    return new KeyPair(publicKey, key);

}