Android设备默认情况下会拒绝使用经过自签名的CA证书,因此需要使用证书授权机构(CA)来签名证书。以下是使用Bouncy Castle库创建自签名证书和CA证书的示例代码:
第一步是创建CA证书和私钥。这里使用RSA算法和SHA256散列:
Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGenerator.initialize(2048, new SecureRandom());
KeyPair caKeyPair = keyPairGenerator.generateKeyPair();
X509v3CertificateBuilder caCertBuilder =
new JcaX509v3CertificateBuilder(new X500Name("CN=MyCA"), BigInteger.valueOf(1),
new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000),
new Date(System.currentTimeMillis() + 10 * 365 * 24 * 60 * 60 * 1000),
new X500Name("CN=MyCA"), caKeyPair.getPublic());
ContentSigner signer =
new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC")
.build(caKeyPair.getPrivate());
X509Certificate caCert = new JcaX509CertificateConverter().setProvider("BC")
.getCertificate(caCertBuilder.build(signer));
第二步是创建服务器证书和私钥,并将其用CA证书签名:
KeyPair serverKeyPair = keyPairGenerator.generateKeyPair();
X509v3CertificateBuilder serverCertBuilder =
new JcaX509v3CertificateBuilder(caCert.getSubject(), BigInteger.valueOf(1),
new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000),
new Date(System.currentTimeMillis() + 10 * 365 * 24 * 60 * 60 * 1000),
new X500Name("CN=MyServer"), serverKeyPair.getPublic());
signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC")
.build(caKeyPair.getPrivate());
X509Certificate serverCert = new Jca