问题
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