參考資料: 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")
沒有留言:
張貼留言