Using BouncyCastle, how do I generate a certificate for any kind of key algorithm?

天大地大妈咪最大 提交于 2021-01-29 07:03:15

问题


I want to store a KeyPair inside AndroidKeyStore, which requires creating a certificate. This answer worked fine for RSA keys, but the KeyPair in my case is supplied by an ssh library and can be several kinds of keys, including DSA, RSA, EC and Ed25519 keys.

I came up with this code, which seems to work:

private interface SignerBuilder {
    BcContentSignerBuilder make(AlgorithmIdentifier sigAlgId, 
                                AlgorithmIdentifier digAlgId);
}

// adapted from answer by Tolga Okur https://stackoverflow.com/a/59182063/1449683
public static X509Certificate generateCertificate(KeyPair keyPair)
        throws IOException, OperatorCreationException, CertificateException {
    ...
    String signingAlgorithm;
    SignerBuilder signerBuilder;
    switch (keyAlgorithm) {
        case "RSA":
            signingAlgorithm = "SHA256withRSA";
            signerBuilder = BcRSAContentSignerBuilder::new;
            break;
        case "EC":
            signingAlgorithm = "SHA256withECDSA";
            signerBuilder = BcECContentSignerBuilder::new;
            break;
        case "DSA":
            signingAlgorithm = "SHA256withDSA";
            signerBuilder = BcDSAContentSignerBuilder::new;
            break;
        default:
            throw new RuntimeException("Can't make a certificate for a key algorithm " + keyAlgorithm);
    }
    ...
    ContentSigner signer = signerBuilder.make(sigAlgId, digAlgId).build(keyParam);
    ...
}

But— I am hardcoding everything here, and this perhaps might fail for some keys, and this doesn't feel future-proof. Is there a better way of obtaining signingAlgorithm and ContentSigner?

来源:https://stackoverflow.com/questions/63677022/using-bouncycastle-how-do-i-generate-a-certificate-for-any-kind-of-key-algorith

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!