StringUtils.kt 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package im.angry.openeuicc.util
  2. fun String.decodeHex(): ByteArray {
  3. require(length % 2 == 0) { "Must have an even length" }
  4. val decodedLength = length / 2
  5. val out = ByteArray(decodedLength)
  6. for (i in 0 until decodedLength) {
  7. val i2 = i * 2
  8. out[i] = substring(i2, i2 + 2).toInt(16).toByte()
  9. }
  10. return out
  11. }
  12. fun ByteArray.encodeHex(): String {
  13. val sb = StringBuilder()
  14. val length = size
  15. for (i in 0 until length) {
  16. sb.append(String.format("%02X", this[i]))
  17. }
  18. return sb.toString()
  19. }
  20. fun formatFreeSpace(size: Int): String =
  21. // SIM cards probably won't have much more space anytime soon.
  22. if (size >= 1024) {
  23. "%.2f KiB".format(size.toDouble() / 1024)
  24. } else {
  25. "$size B"
  26. }
  27. /**
  28. * Decode a list of potential ISDR AIDs, one per line. Lines starting with '#' are ignored.
  29. * If none is found, at least EUICC_DEFAULT_ISDR_AID is returned
  30. */
  31. fun parseIsdrAidList(s: String): List<ByteArray> =
  32. s.split('\n')
  33. .map(String::trim)
  34. .filter { !it.startsWith('#') }
  35. .map(String::trim)
  36. .filter(String::isNotEmpty)
  37. .mapNotNull { runCatching(it::decodeHex).getOrNull() }
  38. .ifEmpty { listOf(EUICC_DEFAULT_ISDR_AID.decodeHex()) }