Android Question Use custom SSL in httpjob - is it possible...

Magma

Expert
Licensed User
Longtime User
Well, trying to use a custom pfx already converted in bks using keytool...

With the help of forum until now... and some knowledge have from b4j i am at this point:

my main code:
B4X:
#AdditionalJar: bcprov-jdk15to18-1.81

.....

Sub GetCustomSSLSocketFactory As Object
    Try
        Dim keystore As JavaObject
        keystore.InitializeNewInstance("java.security.KeyStore", Array("BKS"))
      
        Dim inp As InputStream = File.OpenInput(File.DirAssets, "mykeystore.bks")
      
        Dim pw As String = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"  ' your keystore password
        Dim charArray As Object = StringToCharArray(pw)
      
        keystore.RunMethod("load", Array(inp, charArray))
        inp.Close
      
        Dim tmf As JavaObject
        tmf.InitializeNewInstance("javax.net.ssl.TrustManagerFactory", Array("X509"))
        tmf.RunMethod("init", Array(keystore))
      
        Dim context As JavaObject
        context.InitializeStatic("javax.net.ssl.SSLContext")
        Dim sslcontext As JavaObject = context.RunMethod("getInstance", Array("TLS"))
        sslcontext.RunMethod("init", Array(Null, tmf.RunMethod("getTrustManagers", Null), Null))
      
        Return sslcontext.RunMethod("getSocketFactory", Null)
    Catch
        Log("Error creating SSL context: " & LastException)
        Return Null
    End Try
End Sub



Sub InitSecureHttpClient
    Try
        ' Step 1: Create Java OkHttpClient
        Dim builder As JavaObject
        builder.InitializeNewInstance("okhttp3.OkHttpClient$Builder", Null)

        Dim sslFactory As Object = GetCustomSSLSocketFactory
        If sslFactory = Null Then
            Log("Failed to build SSL Factory")
            Return
        End If

        builder.RunMethod("sslSocketFactory", Array(sslFactory, Null))
        Dim javaClient As Object = builder.RunMethod("build", Null)

        ' Step 2: Assign it to a B4A OkHttpClient
        GlobalSecureClient.Initialize("secure")
        Dim joSecure As JavaObject = GlobalSecureClient
        joSecure.SetField("client", javaClient)

    Catch
        Log("InitSecureHttpClient error: " & LastException)
    End Try
End Sub




Sub StringToCharArray(pw As String) As Object
    Dim jo As JavaObject
    Return jo.InitializeStatic("java.lang.String").RunMethod("toCharArray", Null).As(Object)
End Sub


with the help of AI - found that must pass the ssl to client somehow like that - but this is my problem - i think (may be not easy to use httpjob) - or need a special setup ??
B4X:
        Dim j As HttpJob
        j.Initialize("job111", Me)
      
        Dim m As Map
        m.Initialize
        m.Put("mything",mystring)

      
        Dim json1 As JSONGenerator
        json1.Initialize(m)
      

        j.PostString(Main.urllic & "/getpin",json1.ToString) ',Array(json1.ToString)
        J.GetRequest.SetContentType("application/json")
      
            'custom ssl here... hmmm (ofcourse there is no hc...)
            Dim joReq As JavaObject = j.GetRequest
            joReq.SetField("hc", Main.GlobalSecureClient)
            '-----------
  
        wait for (j) JobDone(j As HttpJob)
      
            Log(j.GetString)
      
        If j.Success Then
              
                Dim json2 As JSONParser
                json2.Initialize(j.GetString)
                Dim m2 As Map = json2.NextObject
          
                If m2.ContainsKey("error") Then
                    If m2.Get("error")=True Then
                        ....
                    End If
                Else
...
                End If

        Else
            Log("Unknown Error")
        End If
    Catch
        Log(LastException)
    End Try

but in httpjob... there is no hc - any idea how i will pass my ssl / cert?
 

walterf25

Expert
Licensed User
Longtime User
Well, trying to use a custom pfx already converted in bks using keytool...

With the help of forum until now... and some knowledge have from b4j i am at this point:

my main code:
B4X:
#AdditionalJar: bcprov-jdk15to18-1.81

.....

Sub GetCustomSSLSocketFactory As Object
    Try
        Dim keystore As JavaObject
        keystore.InitializeNewInstance("java.security.KeyStore", Array("BKS"))
     
        Dim inp As InputStream = File.OpenInput(File.DirAssets, "mykeystore.bks")
     
        Dim pw As String = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"  ' your keystore password
        Dim charArray As Object = StringToCharArray(pw)
     
        keystore.RunMethod("load", Array(inp, charArray))
        inp.Close
     
        Dim tmf As JavaObject
        tmf.InitializeNewInstance("javax.net.ssl.TrustManagerFactory", Array("X509"))
        tmf.RunMethod("init", Array(keystore))
     
        Dim context As JavaObject
        context.InitializeStatic("javax.net.ssl.SSLContext")
        Dim sslcontext As JavaObject = context.RunMethod("getInstance", Array("TLS"))
        sslcontext.RunMethod("init", Array(Null, tmf.RunMethod("getTrustManagers", Null), Null))
     
        Return sslcontext.RunMethod("getSocketFactory", Null)
    Catch
        Log("Error creating SSL context: " & LastException)
        Return Null
    End Try
End Sub



Sub InitSecureHttpClient
    Try
        ' Step 1: Create Java OkHttpClient
        Dim builder As JavaObject
        builder.InitializeNewInstance("okhttp3.OkHttpClient$Builder", Null)

        Dim sslFactory As Object = GetCustomSSLSocketFactory
        If sslFactory = Null Then
            Log("Failed to build SSL Factory")
            Return
        End If

        builder.RunMethod("sslSocketFactory", Array(sslFactory, Null))
        Dim javaClient As Object = builder.RunMethod("build", Null)

        ' Step 2: Assign it to a B4A OkHttpClient
        GlobalSecureClient.Initialize("secure")
        Dim joSecure As JavaObject = GlobalSecureClient
        joSecure.SetField("client", javaClient)

    Catch
        Log("InitSecureHttpClient error: " & LastException)
    End Try
End Sub




Sub StringToCharArray(pw As String) As Object
    Dim jo As JavaObject
    Return jo.InitializeStatic("java.lang.String").RunMethod("toCharArray", Null).As(Object)
End Sub


with the help of AI - found that must pass the ssl to client somehow like that - but this is my problem - i think (may be not easy to use httpjob) - or need a special setup ??
B4X:
        Dim j As HttpJob
        j.Initialize("job111", Me)
     
        Dim m As Map
        m.Initialize
        m.Put("mything",mystring)

     
        Dim json1 As JSONGenerator
        json1.Initialize(m)
     

        j.PostString(Main.urllic & "/getpin",json1.ToString) ',Array(json1.ToString)
        J.GetRequest.SetContentType("application/json")
     
            'custom ssl here... hmmm (ofcourse there is no hc...)
            Dim joReq As JavaObject = j.GetRequest
            joReq.SetField("hc", Main.GlobalSecureClient)
            '-----------
 
        wait for (j) JobDone(j As HttpJob)
     
            Log(j.GetString)
     
        If j.Success Then
             
                Dim json2 As JSONParser
                json2.Initialize(j.GetString)
                Dim m2 As Map = json2.NextObject
         
                If m2.ContainsKey("error") Then
                    If m2.Get("error")=True Then
                        ....
                    End If
                Else
...
                End If

        Else
            Log("Unknown Error")
        End If
    Catch
        Log(LastException)
    End Try

but in httpjob... there is no hc - any idea how i will pass my ssl / cert?
I got the following code, haven't tried it, so don't know if it will work any better.

B4X:
Dim j As HttpJob
j.Initialize("job111", Me)

Dim m As Map
m.Initialize
m.Put("mything", mystring)

Dim json1 As JSONGenerator
json1.Initialize(m)

j.PostString(Main.urllic & "/getpin", json1.ToString)
j.GetRequest.SetContentType("application/json")

' Load your custom SSL certificate (for example, from assets)
Dim certInputStream As InputStream
certInputStream = File.OpenInput(File.DirAssets, "my_custom_cert.pem") ' Replace with your certificate file

' Create a KeyStore and load the certificate
Dim keystore As JavaObject
keystore = keystore.InitializeNewInstance("java.security.KeyStore", Null)
keystore.RunMethod("load", Array(certInputStream, Null))

' Create an SSLContext using the KeyStore
Dim sslContext As JavaObject
sslContext = sslContext.InitializeNewInstance("javax.net.ssl.SSLContext", Null)
sslContext.RunMethod("init", Array(Null, Null, Null)) ' You may need to provide a TrustManager here for validation

' Set the SSLSocketFactory with your custom certificate
Dim sslSocketFactory As JavaObject
sslSocketFactory = sslContext.RunMethod("getSocketFactory", Null)

' Set the custom SSL context on the HttpJob request
Dim joReq As JavaObject = j.GetRequest
joReq.SetField("setSSLSocketFactory", sslSocketFactory)

' Wait for the job to finish
Wait for (j) JobDone(j As HttpJob)

If j.Success Then
    Log(j.GetString)
    Dim json2 As JSONParser
    json2.Initialize(j.GetString)
    Dim m2 As Map = json2.NextObject
    
    If m2.ContainsKey("error") Then
        If m2.Get("error") = True Then
            ' Handle error
        End If
    Else
        ' Handle success
    End If
Else
    Log("Unknown Error")
End If
 
Upvote 0

drgottjr

Expert
Licensed User
Longtime User
i'm tied up with something else right now, but check out this sub from some old projects. if you set the conditional compiler HU2_PUBLIC, you have access to the client. i was testing okhttp3's so-called "interceptor", which - in turn - would have to be connected to our okhttputils' client. maybe something similar for your case.

B4X:
Sub SetInterceptor
    'HU2_PUBLIC
    Dim jo As JavaObject = HttpUtils2Service.hc
    Dim builder As JavaObject = jo.RunMethod("sharedInit", Array("hc"))
'    builder.RunMethod("followRedirects", Array(False))
'    builder.RunMethod("followSslRedirects", Array(False))
    Dim ginterceptor As JavaObject
    ginterceptor.InitializeNewInstance(Application.PackageName & ".main$Ginterceptor",Null)
    builder.runmethod("addNetworkInterceptor", Array (ginterceptor))
    jo.SetField("client", builder.RunMethod("build", Null))
End Sub
 
Upvote 0

Magma

Expert
Licensed User
Longtime User
?
This might help you:
This solved everything... it was just so simple... with Erel's solution... with one call of custom certificate all worked !

Thank you all guys... for your support !
 
Upvote 0
Top