-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: add base 58 check for gateway identity keys (#2312)
- Loading branch information
1 parent
9e8735f
commit 0721317
Showing
3 changed files
with
52 additions
and
6 deletions.
There are no files selected for viewing
45 changes: 45 additions & 0 deletions
45
nym-vpn-android/core/src/main/java/net/nymtech/vpn/util/Base58.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package net.nymtech.vpn.util | ||
|
||
import java.math.BigInteger | ||
|
||
object Base58 { | ||
private const val ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" | ||
private val INDEXES = IntArray(128) { -1 }.also { | ||
for (i in ALPHABET.indices) { | ||
it[ALPHABET[i].code] = i | ||
} | ||
} | ||
|
||
fun isValidBase58(input: String, expectedByteLength: Int = 32): Boolean { | ||
try { | ||
if (input.isEmpty() || input.any { it.code >= 128 || INDEXES[it.code] == -1 }) { | ||
return false | ||
} | ||
|
||
val bytes = decode(input) | ||
|
||
return bytes.size == expectedByteLength | ||
} catch (e: Exception) { | ||
return false | ||
} | ||
} | ||
|
||
private fun decode(input: String): ByteArray { | ||
if (input.isEmpty()) return ByteArray(0) | ||
|
||
val bigInt = input.fold(BigInteger.ZERO) { acc, char -> | ||
val index = INDEXES[char.code] | ||
if (index == -1) throw IllegalArgumentException("Invalid Base58 character: $char") | ||
acc.multiply(BigInteger.valueOf(58)).add(BigInteger.valueOf(index.toLong())) | ||
} | ||
|
||
val bytes = bigInt.toByteArray() | ||
|
||
val leadingZeros = input.takeWhile { it == '1' }.length | ||
return if (bytes[0].toInt() == 0 && bytes.size > 1) { | ||
ByteArray(leadingZeros) + bytes.drop(1).toByteArray() | ||
} else { | ||
ByteArray(leadingZeros) + bytes | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters