How to use .key and .pem file to create a socket S

2019-05-01 19:12发布

问题:

My .key file like: -----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEA1j6eGXbHpqigZ1K//wnuyr5v/L2jFm7dzTtHJx8ZoMQ4CbsG

My .pem file like: -----BEGIN CERTIFICATE----- MIIE4zCCA8ugAwIBAgIDBOziMA0GCSqGSIb3DQEBBQUAMDwxCzAJBgNVBAYTAlVT

I don't know how many steps of authenticate at here. I only want to create a ssl socket to an IP and port, and send/receive data in that socket. I tried to use keystock, but perhaps I don't understand deep about it, I always get wrong.

Please give me a guide, or sample code.

Thanks so much.

回答1:

I assume that the .key and .pem file represents your client certificate you have to use for performing an HTTPS client authentication. Unfortunately Java/Android prefers a different format, therefore I recommend you to import both file into a BKS file.

Creating a BKS file and importing existing .key+.pem file is very simple using Portecle GUI. After starting Portecle select File -> New Keystore -> BKS. Afterwards you can execute Tools -> Import Key Pair and select the .pem file. Afterwards Portecle will ask you for selecting the .key file.

Finally save the key store protected with a password of your choice.

The created BKS file can now be used in your Android app. See for example the code posted in this question: Using client/server certificates for two way authentication SSL socket on Android

Update 2015-06-30: The description above works only for Portecle 1.6 and before. With version 1.7 and 1.8 you can not create android compatible keystores. In Portecle 1.9 use the format BKS-V1 instead.



回答2:

When creating a SSL connection, you just need the socket to allow the connection with your server, enabling it as a trusted source. To do so, you need to have your SSL certificate in X509 format and then create your connection as stated in this article.

Here's a guide on generating X.509 certificates.