All Downloads are FREE. Search and download functionalities are using the official Maven repository.

pto.0.3.0.source-code.Utils.kt Maven / Gradle / Ivy

There is a newer version: 0.3.1
Show newest version
package se.wollan.crypto

import java.util.Base64

internal fun String.fromBase64(): ByteArray = Base64.getDecoder().decode(this)

internal fun ByteArray.toBase64(): String = Base64.getEncoder().encodeToString(this)

internal fun ByteArray.toStringUTF8(): String = toString(Charsets.UTF_8)

@OptIn(ExperimentalStdlibApi::class)
internal fun ByteArray.toHexString(): String = toHexString(HexFormat.Default)

@OptIn(ExperimentalStdlibApi::class)
internal fun String.fromHexString(): ByteArray = hexToByteArray(HexFormat.Default)

internal fun ByteArray.xor(second: ByteArray): ByteArray {
    require(size == second.size) { "Arrays must have the same length, $size != ${second.size}." }

    val result = ByteArray(size)
    for (i in indices) {
        result[i] = (this[i].toInt() xor second[i].toInt()).toByte()
    }

    return result
}

internal fun ByteArray.pad(finalLength: Int, paddingByte: Byte): ByteArray {
    require(finalLength >= size) { "Final length ($finalLength) must be greater than or equal to the length of the data ($size)." }

    val paddingLength = finalLength - size
    val padding = ByteArray(paddingLength) { paddingByte }

    val paddedData = ByteArray(size + paddingLength)
    System.arraycopy(this, 0, paddedData, 0, size)
    System.arraycopy(padding, 0, paddedData, size, paddingLength)

    return paddedData
}

internal fun ByteArray.unpad(paddingByte: Byte): ByteArray {
    var paddingStart = size
    while (paddingStart > 0 && this[paddingStart - 1] == paddingByte) {
        paddingStart--
    }
    return copyOfRange(0, paddingStart)
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy