Как перевести String в шестнадцатеричную систему счисления и обратно
Как перевести String в шестнадцатеричную систему счисления и обратно.
String url="1egwMxTKMsXQzs-SYdrGB-F8m5h0AEMQg";
Ответы (2 шт):
Есть такой пакетик DatatypeConverter, в котором если на вход подать массив байтов, то можно получить все что угодно. Вопрос только в том, как получить из строки байты. По хорошему метод String.getBytes() делает это, но проблема в том, что при этом используется текущая локаль/кодировка. Чтобы не зависеть от локали, надо явно указывать кодировку, примерно так.
String hex=DatatypeConverter.printHexBinary(input.getBytes("UTF-8"));
Для шифрования базы можно использовать обычный xor:
private const val SECRET = "you key"
object Base64Xor {
fun encode(s: String, key: String = SECRET): String {
return Base64.encodeBase64ToString(xorWithKey(s.toByteArray(), key.toByteArray()))
}
fun decode(s: String, key: String = SECRET): String {
return String(xorWithKey(Base64.decodeBase64ToByteArray(s), key.toByteArray()))
}
private fun xorWithKey(a: ByteArray, key: ByteArray): ByteArray {
val out = ByteArray(a.size)
for (i in a.indices) {
out[i] = (a[i] xor key[i % key.size]) as Byte
}
return out
}
}
В области компьютерных наук Base64 представляет собой группу схем кодирования двоичного текста в текст, которые представляют двоичные данные в строковом формате ASCII, переводя их в представление radix-64. Термин Base64 происходит от конкретной кодировки передачи содержимого MIME. Каждая цифра Base64 представляет ровно 6 бит данных. Таким образом, три 8-битных байта (то есть всего 24 бита) могут быть представлены четырьмя 6-битными цифрами Base64. (ист. Википедия)
object Base64 {
fun encodeBase64ToString(input: String): String = String(input.toByteArray().encodeBase64())
fun encodeBase64ToByteArray(input: String): ByteArray = input.toByteArray().encodeBase64()
fun encodeBase64ToString(input: ByteArray): String = String(input.encodeBase64())
fun decodeBase64(input: String): String = String(input.toByteArray().decodeBase64())
fun decodeBase64ToByteArray(input: String): ByteArray = input.toByteArray().decodeBase64()
fun decodeBase64ToString(input: ByteArray): String = String(input.decodeBase64())
fun ByteArray.encodeBase64(): ByteArray {
val table = (CharRange('A', 'Z') + CharRange('a', 'z') + CharRange('0', '9') + '+' + '/' + '=').toCharArray()
val output = ByteArrayOutputStream()
var padding = 0
var position = 0
while (position < this.size) {
var b = this[position].toInt() and 0xFF shl 16 and 0xFFFFFF
if (position + 1 < this.size) b = b or (this[position + 1].toInt() and 0xFF shl 8) else padding++
if (position + 2 < this.size) b = b or (this[position + 2].toInt() and 0xFF) else padding++
for (i in 0 until 4 - padding) {
val c = b and 0xFC0000 shr 18
output.write(table[c].toInt())
b = b shl 6
}
position += 3
}
for (i in 0 until padding) {
output.write('='.toInt())
}
return output.toByteArray()
}
fun ByteArray.decodeBase64(): ByteArray {
val table = intArrayOf(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1,
-1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
val output = ByteArrayOutputStream()
var position = 0
while (position < this.size) {
var b: Int
if (table[this[position].toInt()] != -1) {
b = table[this[position].toInt()] and 0xFF shl 18
} else {
position++
continue
}
var count = 0
if (position + 1 < this.size && table[this[position + 1].toInt()] != -1) {
b = b or (table[this[position + 1].toInt()] and 0xFF shl 12)
count++
}
if (position + 2 < this.size && table[this[position + 2].toInt()] != -1) {
b = b or (table[this[position + 2].toInt()] and 0xFF shl 6)
count++
}
if (position + 3 < this.size && table[this[position + 3].toInt()] != -1) {
b = b or (table[this[position + 3].toInt()] and 0xFF)
count++
}
while (count > 0) {
val c = b and 0xFF0000 shr 16
output.write(c.toChar().toInt())
b = b shl 8
count--
}
position += 4
}
return output.toByteArray()
}
}
В сумме вы получаете надежные механизм шифровки своих данных.