Monday, November 18, 2019

app-debug.apk test using emulator avd command prompt

START EMULATOR

C:\Users\home>emulator -list-avds
Pixel_XL_API_22

C:\Users\home>emulator -avd Pixel_XL_API_22
emulator: WARNING: encryption is off
Warning: Quick Boot / Snapshots not supported on this machine. A CPU with EPT +
UG features is currently needed. We will address this in a future release.
emulator: WARNING: Not all modern X86 virtualization features supported, which i
ntroduces problems with slowdown when running Android on multicore vCPUs. Settin
g AVD to run with 1 vCPU core only.
emulator: WARNING: Your GPU drivers may have a bug. Switching to software render
ing.
HAX is working and emulator runs in fast virt mode.


RUN APK on EMULATOR

C:\Users\home>adb devices
List of devices attached
emulator-5554   device


C:\Users\home>adb -e install -r D:\app-debug.apk
Performing Push Install
D:\app-debug.apk: 1 file pushed. 35.9 MB/s (19761823 bytes in 0.525s)
        pkg: /data/local/tmp/app-debug.apk
Success

C:\Users\home>

Thursday, November 7, 2019

Security with HTTPS and SSL socket client creating with Trusted Certificate, KeyStore, bks type

private fun createHttpClient(): HttpClient {
        var httpClient: HttpClient? = null        try {
            val is_unsafe = AppConfig.current.getApiItem("unsafe").toBoolean()
            val requestConfig = RequestConfig.custom().setCircularRedirectsAllowed(true).build()

            var trustAllCerts = arrayOf<TrustManager>()
            val sslContext = SSLContext.getInstance(ConstVariables.SSLContext_TLS)
            if (is_unsafe) {
                trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
                    override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
                    override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) = Unit
                    override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) = Unit
                })
                sslContext.init(null, trustAllCerts, SecureRandom())
            } else {
                var keyStore = App.getTrustedKeyStore()
                var trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
                trustManagerFactory.init(keyStore)
//                val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())//                keyManagerFactory.init(keyStore, null)                sslContext.init(null, trustManagerFactory.trustManagers, SecureRandom())
            }

            var sslsf = SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE)
            var socketFactoryRegistry = RegistryBuilder.create<ConnectionSocketFactory>()
                    .register("https", sslsf).build()//.register("http", PlainConnectionSocketFactory())
            var connectionManager = BasicHttpClientConnectionManager(socketFactoryRegistry)
            httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
                    .setConnectionManager(connectionManager).build()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return httpClient as HttpClient
    }
**********************************************************************
private fun makeSocket(roomInfo: JSONObject): Socket? {
        if (mSocket != null)
            return mSocket        else {
            try {
                val is_unsafe = AppConfig.current.getApiItem("unsafe").toBoolean()
                val bot_timeout = AppConfig.current.getApiItem("bot_timeout").toLong()

                var trustAllCerts = arrayOf<TrustManager>()
                val sslContext = SSLContext.getInstance(ConstVariables.SSLContext_TLS)
                var trustManager: X509TrustManager? = null                if (is_unsafe) {
                    trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
                        override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
                        override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) = Unit
                        override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) = Unit
                    })
                    sslContext.init(null, trustAllCerts, SecureRandom())

                    trustManager = trustAllCerts.get(0) as X509TrustManager
                } else {
                    var keyStore = App.getTrustedKeyStore()
                    var trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
                    trustManagerFactory.init(keyStore)
//                    val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())//                    keyManagerFactory.init(keyStore, null)                    sslContext.init(null, trustManagerFactory.trustManagers, SecureRandom())

                    trustManager = trustManagerFactory.trustManagers.get(0) as X509TrustManager
                }

                //val trustManager = trustManagerFactory.trustManagers.get(0) as X509TrustManager                val okHttpClient = OkHttpClient.Builder().hostnameVerifier(NoopHostnameVerifier.INSTANCE)
                        .sslSocketFactory(sslContext.getSocketFactory(), trustManager)
                        .cookieJar(makeCookieJar())
                        .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(bot_timeout, TimeUnit.SECONDS).writeTimeout(bot_timeout, TimeUnit.SECONDS)
                        .build()

                val options = IO.Options()
                //options.query = ("authtoken=" + AppSharedPrefrence.getString(this, App..AUTH_TOKEN))                options.forceNew = AppConfig.current.getApiItem("bot_forceNew").toBoolean()
                options.secure = AppConfig.current.getApiItem("bot_secure").toBoolean()
                options.callFactory = okHttpClient
                options.webSocketFactory = okHttpClient
                options.transports = arrayOf(WebSocket.NAME, Polling.NAME)
                val botUrl = UrlHelper.botUrl("room-" + roomInfo.getInt("id"))
                mSocket = IO.socket(botUrl, options)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return mSocket    }
**********************************************************************
fun getTrustedKeyStore(): KeyStore {
    if (trusted != null) return trusted as KeyStore
    val caInput = resource.openRawResource(R.raw.server)
    val cf = CertificateFactory.getInstance("X.509")
    val ca: Certificate
    try {
        ca = cf.generateCertificate(caInput)
        System.out.println("ca=" + (ca as X509Certificate).getSubjectDN())
    } finally {
        caInput.close()
    }

    // Create a KeyStore containing our trusted CAs    val keyStoreType = KeyStore.getDefaultType()
    val keyStore = KeyStore.getInstance(keyStoreType)
    keyStore.load(null, null)
    keyStore.setCertificateEntry("ca", ca)
    if (keyStoreType == ConstVariables.KeyStore_BKS) {
        return keyStore
    } else {
        var host = AppConfig.current.getApiItem("host")
        var hi = host.indexOf(':')
        var hip = host.substring(0, hi)
        var hips = hip.split('.')
        var ks = "ks_" + hips[2] + "_" + hips[3]
        var rid = ResourceHelper.getResourceId(ks, "raw")
        trusted = KeyStore.getInstance(ConstVariables.KeyStore_BKS)
        var ins = if (AppConfig.isApiRunatDevMode()) resource.openRawResource(rid)
        else resource.openRawResource(R.raw.key_store)//key_store.bks        try {
            trusted?.load(ins, null)
        } finally {
            ins.close()
            return trusted as KeyStore
        }
    }
}

Hide automatically the navigation bar in code behind using custom library with OnSystemUiVisibilityChangeListener

package mn.ho.mypoker.libraries.views

import android.os.Handler
import android.view.View
import android.view.Window


class SystemUiVisibilityHider(w: Window) : View.OnSystemUiVisibilityChangeListener {
    private var window: Window = w
    private var isFlagHideSystemUI = false    private var flagHideSystemUI = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE            or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION            or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN            or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION            or View.SYSTEM_UI_FLAG_FULLSCREEN            or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)

    init {
        this.window.decorView.setOnSystemUiVisibilityChangeListener(this)
    }

    override fun onSystemUiVisibilityChange(visibility: Int) {
        if (this.window.decorView.systemUiVisibility != flagHideSystemUI) {
            Handler().postDelayed({                isFlagHideSystemUI = false            }, 1000)
        }
    }

    fun run() {
        if (this.window.decorView.systemUiVisibility != flagHideSystemUI) {
            isFlagHideSystemUI = true            this.window.decorView.systemUiVisibility = flagHideSystemUI        }
    }
}

on Activity

override fun onTouchEvent(event: MotionEvent?): Boolean {
    sysNavHider?.run()
    return super.onTouchEvent(event)
}

how to install app-debug.apk file into android phone using command prompt shell

#-t is test only
#-r is reinstall
adb devices
List of devices attached
06157df6848f6a14        device
LGMS55017965c0d device
f89c9b8f        device

adb push app-debug.apk /tmp/
pm install /tmp/app-debug.apk
#if Failure [INSTALL_FAILED_INVALID_URI]

#then use android phone shell command
adb -s 06157df6848f6a14 shell
pm install -t -r /sdcard/Download/app-debug.apk

or using Terminal Emulator App