package com.ysnows.base.net

import com.ysnows.base.base.BApp
import com.ysnows.base.utils.Base64Util
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.security.KeyFactory
import java.security.NoSuchAlgorithmException
import java.security.PublicKey
import java.security.spec.X509EncodedKeySpec

import javax.crypto.Cipher


/**
 *Created by shihuiyun
 *on 2020/11/9
 */
class CommonInterceptor() : Interceptor {



    override fun intercept(chain: Interceptor.Chain): Response {
        val oldRequest: Request = chain.request()

        var time=( System.currentTimeMillis()/1000).toString()

//        Log.e("-shy-", "time=: $time")

        var keyTime=encryptByPublic(time!!, BApp.instance()!!.config()!!.publicKey())

//        Log.e("-shy-", "keyTime=: $keyTime")


        // 添加新的参数
        val authorizedUrlBuilder: HttpUrl.Builder = oldRequest.url()
                .newBuilder()
                .scheme(oldRequest.url().scheme())
                .host(oldRequest.url().host())
                .addQueryParameter(BApp.instance()!!.config()!!.publicKeyName(), keyTime)
                .addQueryParameter(BApp.instance()!!.config()!!.keyName(), time)

        // 新的请求

        // 新的请求
        val newRequest: Request = oldRequest.newBuilder()
                .method(oldRequest.method(), oldRequest.body())
                .url(authorizedUrlBuilder.build())
                .build()

        return chain.proceed(newRequest)
    }


    /**
     * 得到公钥
     *
     * @param bysKey
     * @return
     */
    @Throws(NoSuchAlgorithmException::class, java.lang.Exception::class)
    private fun getPublicKeyFromX509(bysKey: String): PublicKey? {
        val decodedKey: ByteArray = Base64Util.decode(bysKey)
        val x509 = X509EncodedKeySpec(decodedKey)
        val keyFactory: KeyFactory = KeyFactory.getInstance("RSA")
        return keyFactory.generatePublic(x509)
    }

    /**
     * 使用公钥加密
     *
     * @param content 密文
     * @param pub_key 公钥
     * @return
     */
    fun encryptByPublic(content: String, pub_key: String?): String? {
        return try {
            val pubkey = getPublicKeyFromX509(pub_key!!)
            val cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")
            cipher.init(Cipher.ENCRYPT_MODE, pubkey)
            val plaintext = content.toByteArray(charset("UTF-8"))
            val output = cipher.doFinal(plaintext)
            (Base64Util.encode(output)).toString()
        } catch (e: java.lang.Exception) {
            null
        }
    }



}
