B4J Code Snippet [B4X] Trust all SSL Socket

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")

If you are building a standalone package then add this:
B4X:
#PackagerProperty: VMArgs = --add-opens java.base/sun.security.ssl=b4j
 
Last edited:

juvanum

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

juvanum

Active Member
Licensed User
Longtime 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?
 

Magma

Expert
Licensed User
Longtime 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... ?
 

OliverA

Expert
Licensed User
Longtime User
b4j but can't for b4a
It's part of B4A's Network library. As per post#1, you don't need the code in post#1 for B4A, but use B4A's InitializeSSLAcceptAll method of the Socket class (as per post#2).
 

DonManfred

Expert
Licensed User
Longtime User
Top