【问题标题】:Generate KeyPair using Public and Private JKS files使用公共和私有 JKS 文件生成密钥对
【发布时间】:2017-01-18 20:52:32
【问题描述】:

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

谢谢

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

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

【问题讨论】:

    标签: java keystore key-pair


    【解决方案1】:

    你可以像下面这样使用:

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

    【讨论】:

    • 对于参数“final File keystoreFile”,我们传递的是公钥还是私钥?
    • 当我加载私钥库时,我收到此代码的异常Exception in thread "main" java.security.UnrecoverableKeyException: Cannot recover key
    • 啊问题是证书和密钥都有不同的密码,所以我需要同时通过密钥和证书通行证。我稍微更新了代码,它可以工作了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 2014-09-27
    • 2011-01-29
    • 2015-12-28
    • 2023-03-14
    相关资源
    最近更新 更多