我正在开发一个Android项目。我有一个PEM证书字符串:
-----BEGIN CERTIFICATE-----
MIIEczCCA1ugAwIBAgIBADANBgkqhkiG9w0BAQQFAD..AkGA1UEBhMCR0Ix
EzARBgNVBAgTClNvbWUtU3RhdGUxFDASBgNVBAoTC0..0EgTHRkMTcwNQYD
VQQLEy5DbGFzcyAxIFB1YmxpYyBQcmltYXJ5IENlcn..XRpb24gQXV0aG9y
...MANY LINES...
It8una2gY4l2O//on88r5IWJlm1L0oA8e4fR2yrBHX..adsGeFKkyNrwGi/
7vQMfXdGsRrXNGRGnX+vWDZ3/zWI0joDtCkNnqEpVn..HoX
-----END CERTIFICATE-----
(我将上面的证书字符串分配给名为CERT_STR
的变量)
我将以上PEM字符串转换为X509Certificate:
byte[] certBytes = CERT_STR.getBytes();
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
InputStream certIs = new ByteArrayInputStream(certBytes);
// now I get the X509 certificate from the PEM string
X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(certIs);
然后,我尝试通过以下方式以编程方式安装证书:
Intent intent = KeyChain.createInstallIntent();
// because my PEM only contains a certificate, no private key, so I use EXTRA_CERTIFICATE
intent.putExtra(KeyChain.EXTRA_CERTIFICATE, certificate.getEncoded());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
当我运行我的应用程序时,我看到系统对话框弹出“Extracting ...”,我知道系统正在提取我的证书,但该对话框显示始终说“提取......“。
为什么呢?我的代码安装证书在哪里错了?
答案 0 :(得分:3)
您可能没有使用正确创建的X509证书。以下工作结束,我没有看到任何“Extracting ...”对话框(Nexus 5X,Android 7.0):
String x509cert = "-----BEGIN CERTIFICATE-----\n" +
"MIICrjCCAhegAwIBAgIJAO9T3E+oW38mMA0GCSqGSIb3DQEBCwUAMHAxCzAJBgNV\n" +
"BAYTAlVaMREwDwYDVQQHDAhUYXNoa2VudDENMAsGA1UECgwERWZpcjEQMA4GA1UE\n" +
"CwwHSVQgZGVwdDEQMA4GA1UEAwwHZWZpci51ejEbMBkGCSqGSIb3DQEJARYMaG9z\n" +
"dEBlZmlyLnV6MB4XDTE2MTExMDA4MjIzMFoXDTE2MTIxMDA4MjIzMFowcDELMAkG\n" +
"A1UEBhMCVVoxETAPBgNVBAcMCFRhc2hrZW50MQ0wCwYDVQQKDARFZmlyMRAwDgYD\n" +
"VQQLDAdJVCBkZXB0MRAwDgYDVQQDDAdlZmlyLnV6MRswGQYJKoZIhvcNAQkBFgxo\n" +
"b3N0QGVmaXIudXowgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAL60mG0Gpl7s\n" +
"3qMnZcURB1xk5Qen6FN0+AJB5Z/WHA50n1MUkXNY28rkEYupkxpfEqR+/gXgBUAm\n" +
"FACA3GSdoHMMY1kdeAzxsYbBEbtGKHICF/QFGTqScWmI6uBUwzsLDLv1ELef/zEY\n" +
"Ru/krXtNh8ZNYyfwVKyZaB9+3M2yOqATAgMBAAGjUDBOMB0GA1UdDgQWBBS1nH3O\n" +
"ecLDrIZLZ/f1WsNL/xtuEzAfBgNVHSMEGDAWgBS1nH3OecLDrIZLZ/f1WsNL/xtu\n" +
"EzAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4GBAGzjJnXODvF9UHBKHAUF\n" +
"kzisr78Og5BrKyAgdnjH196Jg4MO7RNJdQAmuAIk9aBB/jvAiznhhbcD3mYImH+h\n" +
"F0Scewk5m736ydGhkcUpmxA5ye1hajjs9V7PQD2O4a8rNJSlJjiWRWSqxTfH79Ns\n" +
"B7x2HND9LU/iz02ugGJ8vwg8\n" +
"-----END CERTIFICATE-----\n";
Intent intent = KeyChain.createInstallIntent();
intent.putExtra(KeyChain.EXTRA_CERTIFICATE, x509cert.getBytes());
startActivity(intent);
要生成上述证书,我使用了以下步骤(基于Generating Keys and Certificates for SSO):
$ openssl genrsa -out rsaprivkey.pem 1024
$ openssl req -new -x509 -key rsaprivkey.pem -out rsacert.pem
$ ls
rsacert.pem rsaprivkey.pem
然后,我只需将cat rsacert.pem
的输出复制/粘贴到x509cert
。
希望这有帮助。