SSLSocketFactory in Android
Overview
SSLSocketFactory is used to create secure sockets.
Steps to follow
- First you have to create a key store.
- Open command prompt using Administrator login.
- Type "cd C:\Program Files\Java\jdk-14\bin".
- Type the below command
keytool -genkey -v -keystore my-key.keystore -alias my-key-alias-keyalg RSA -keysize 2048 -validity 10000
- Follow the steps given in the screenshot:
- For -keyalg you can use RSA, DSA, EC to generate asymmetric key pair or use DES, 3DES to generate symmetric key pair.
- Then you have to generate a certificate
- Open command prompt using Administrator login.
- Type "cd C:\Program Files\Java\jdk-14\bin".
- Type the below command
keytool -certreq -alias "my-key-alias" -file mycertreq.csr -keystore my-key.keystore
- Follow the steps given in the screenshot.
- Note: The password, alias name, keystore name must be the same which you used while creating the keystore.
- An example of creating a subclass of SSLSocketFactory
class TLSSocketFactory : SSLSocketFactory() {
private val context = SSLContext.getInstance("TLS")
private var delegate: SSLSocketFactory? = null
private var protocols = arrayOf("TLSv1.2")
init {
context.init(null, null, null)
delegate = context.socketFactory
}
override fun createSocket(s: Socket?, host: String?, port: Int, autoClose: Boolean): Socket {
return this.enableTLSOnSocket(delegate!!.createSocket(s, host, port, autoClose))!!
}
override fun createSocket(host: String?, port: Int): Socket {
return this.enableTLSOnSocket(delegate!!.createSocket(host, port))!!
}
override fun createSocket(
host: String?,
port: Int,
localHost: InetAddress?,
localPort: Int
): Socket {
return this.enableTLSOnSocket(delegate!!.createSocket(host, port, localHost, localPort))!!
}
override fun createSocket(host: InetAddress?, port: Int): Socket {
return this.enableTLSOnSocket(delegate!!.createSocket(host, port))!!
}
override fun createSocket(
address: InetAddress?,
port: Int,
localAddress: InetAddress?,
localPort: Int
): Socket {
return this.enableTLSOnSocket(
delegate!!.createSocket(
address,
port,
localAddress,
localPort
)
)!!
}
override fun getDefaultCipherSuites(): Array<String> {
return delegate!!.defaultCipherSuites
}
override fun getSupportedCipherSuites(): Array<String> {
return protocols
}
private fun enableTLSOnSocket(socket: Socket?): Socket? {
if (socket != null && socket is SSLSocket) {
socket.enabledProtocols = arrayOf("TLSv1.2")
}
return socket;
}
}
Reference
- https://developer.android.com/reference/org/apache/http/conn/ssl/SSLSocketFactory
- https://www.demo2s.com/android/android-sslsocketfactory-tutorial-with-examples.html
- https://stackoverflow.com/questions/57409304/keytool-generate-aes-public-private-key-pair
- https://stackoverflow.com/questions/3997748/how-can-i-create-a-keystore
Comments
Post a Comment