B4J Code Snippet [B4X] Trust all SSL Socket

Erel

Administrator
Staff member
Licensed User
Platforms: B4J (1st post) and B4A (2nd post)

This code creates an SSL socket that doesn't verify the server certificate.

Depends on jNet / Net and JavaObject libraries.

B4X:
Private Sub CreateTrustAllSSLSocket (EventName As String) As Socket
   Dim socket As Socket
   socket.Initialize(EventName)
   Dim jo As JavaObject = socket
   jo.SetField("socket", CreateTrustAllSSLSocketFactory.RunMethod("createSocket", Null))
   Return socket
End Sub

Sub CreateTrustAllSSLSocketFactory As JavaObject
   Dim tm As CustomTrustManager
   tm.InitializeAcceptAll
   Dim SSLContext As JavaObject
   SSLContext = SSLContext.InitializeStatic("javax.net.ssl.SSLContext").RunMethod("getInstance", Array("TLS"))
   SSLContext.RunMethod("init", Array(Null, tm, Null))
   Dim Factory As JavaObject = SSLContext.RunMethod("getSocketFactory", Null)
   Return Factory
End Sub
Usage:
B4X:
Dim sock As Socket = CreateTrustAllSSLSocket("sock")
 
Last edited:

juvanum

Active Member
Licensed User
help me to understand:
does that mean I can not install any certificate on the server and make an https connection?
thanks
 

Erel

Administrator
Staff member
Licensed User
If you install a trusted certificate then you don't need to do anything special. The code above is not required in that case.

If the certificate is not trusted then you need to use the code above to create a socket that doesn't validate the certificate.
 

juvanum

Active Member
Licensed User
If you install a trusted certificate then you don't need to do anything special. The code above is not required in that case.

If the certificate is not trusted then you need to use the code above to create a socket that doesn't validate the certificate.
Thanks but if I have no certificate can I use https to connect to the server using the code above?
 

Erel

Administrator
Staff member
Licensed User
You cannot create a SSL connection if the server doesn't have a certificate. Please start a new thread for further discussion.
 

Magma

Well-Known Member
Licensed User
Hi there... i am searching all over the forum... finding jnet library for b4j but can't for b4a.... can i have a download link please with latest version for b4a...?

by the way need any permission to work... ?
 

Magma

Well-Known Member
Licensed User
Thanks!!!
need any permission to work... to higher versions of Android ?
 

Magma

Well-Known Member
Licensed User
@DonManfred ...Didn't get any error - but needed to know that - because i want it to use at Android 9 Pie versions and haven't for now.... Thanks for the answer :)
 
Top