2021年6月13日 星期日

使用 kotlin 語言把 http 協定連線升級成 WebSocket 協定所需要的回應編碼: base64( sha1(clientKey) )

 參考資料: https://datatracker.ietf.org/doc/html/rfc6455

    // echo -n dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-C5AB0DC85B11 | sha1sum 
    // sha1Hex  : b37a4f2cc0624f1690f64606cf385945b2bec4ea
    // keyBase64: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
   
    val clientKey = "dGhlIHNhbXBsZSBub25jZQ=="  
    val guID      = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
    val base64sym = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
    val key_GUID  = "${clientKey.trim()}$guID"
    val binary    = MessageDigest.getInstance("SHA-1").digest(key_GUID.toByteArray())
    val sha1Hex   = StringBuilder()
    val keyBase64 = StringBuilder()
    val temp3 = IntArray(3)
    var accumulate = 0
    for (c in binary)  {
        sha1Hex.append(String.format("%02x", c))
        temp3[accumulate ++] = c.toInt()
        if (accumulate == 3) {
            accumulate = 0;
            keyBase64.append(base64sym[ (temp3[0] and 0xfc) shr 2])
            keyBase64.append(base64sym[((temp3[0] and 0x03) shl 4) + ((temp3[1] and 0xf0) shr 4)])
            keyBase64.append(base64sym[((temp3[1] and 0x0f) shl 2) + ((temp3[2] and 0xc0) shr 6)])
            keyBase64.append(base64sym[  temp3[2] and 0x3f])
        }
    }
    if (accumulate > 0) {
        keyBase64.append(base64sym[ (temp3[0] and 0xfc) shr 2])
        if (accumulate == 2) {
            keyBase64.append(base64sym[((temp3[0] and 0x03) shl 4) + ((temp3[1] and 0xf0) shr 4)])
            keyBase64.append(base64sym[ (temp3[1] and 0x0f) shl 2])
        }
        keyBase64.append('=')
        if(accumulate == 1) keyBase64.append('=')
    }
    Log.d("WebSocket_key:", "$clientKey, $keyBase64, $sha1Hex") 

沒有留言:

張貼留言

使用 pcie 轉接器連接 nvme SSD

之前 AM4 主機板使用 pcie ssd, 但主機板故障了沒辦法上網, 只好翻出以前買的 FM2 舊主機板, 想辦法讓老主機復活, 但舊主機板沒有 nvme 的界面, 因此上網買了 pcie 轉接器用來連接 nvme ssd, 遺憾的是 grub2 bootloader 無法識...