gpt4 book ai didi

java - 使用 AndroidKeyStoreProvider 生成证书签名请求的最佳方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 10:19:44 34 4
gpt4 key购买 nike

我读了this article .

它说明了如何生成KeyPair,但是它没有指定如何根据生成的 key 生成证书签名请求。

根据我的研究,要用 Java 生成 CSR,来自网络的示例通常使用包 sun.* 或 BouncyCaSTLe 库。似乎没有办法使用标准 java.security API 生成 CSR。我读了this它似乎在说同样的话。

我别无选择,只能使用 BouncyCaSTLe 吗?很难想象 Android 开发者不会考虑这种用法。

顺便说一下,文章中还提到:

Generating a new PrivateKey requires that you also specify theinitial X.509 attributes that the self-signed certificate will have.You can replace the certificate at a later time with a certificatesigned by a Certificate Authority

假设我最终获得了由证书颁发机构签署的证书。我究竟应该怎么做才能“稍后更换证书”?

最佳答案

在 Android 上创建 CSR 的最佳方法是使用 SpongyCastle , 这是 BouncyCastle 的实现对于安卓。 SpongyCaSTLe 已经为您做了很多繁重的工作,所以它会让您的生活更轻松。


我的实现很大程度上基于找到的答案 here ,但使用 Android KeyStore 确保安全,并使用 SpongyCaSTLe 的 JcaContentSignerBuilder() 而不是自定义 ContentSigner

将 SpongyCaSTLe 添加到您的 build.gradle 文件中:

compile 'com.madgag.spongycastle:core:1.51.0.0'
compile 'com.madgag.spongycastle:pkix:1.51.0.0'

Android KeyStore 中创建 key 对:

KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore"); // store the key in the Android KeyStore for security purposes
keyGen.initialize(new KeyGenParameterSpec.Builder(
"key1",
KeyProperties.PURPOSE_SIGN)
.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
.setDigests(KeyProperties.DIGEST_SHA256,
KeyProperties.DIGEST_SHA384,
KeyProperties.DIGEST_SHA512)
.build()); // defaults to RSA 2048
KeyPair keyPair = keyGen.generateKeyPair();

使用上述 key 对创建 CSR:

private final static String CN_PATTERN = "CN=%s, O=Aralink, OU=OrgUnit";

//Create the certificate signing request (CSR) from private and public keys
public static PKCS10CertificationRequest generateCSR(KeyPair keyPair, String cn) throws IOException, OperatorCreationException {
String principal = String.format(CN_PATTERN, cn);

ContentSigner signer = new JcaContentSignerBuilder(DEFAULT_RSA_SIGNATURE_ALGORITHM).build(keyPair.getPrivate());

PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(
new X500Name(principal), keyPair.getPublic());
ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
extensionsGenerator.addExtension(Extension.basicConstraints, true, new BasicConstraints(
true));
csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
extensionsGenerator.generate());
PKCS10CertificationRequest csr = csrBuilder.build(signer);

return csr;
}
}

就是这样,现在您有一个可以发送到服务器的 PKCS10CertificationRequest

关于java - 使用 AndroidKeyStoreProvider 生成证书签名请求的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25907326/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com