forked from sergeych/crypto2
47 lines
1.5 KiB
Kotlin
47 lines
1.5 KiB
Kotlin
/*
|
|
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
|
|
*
|
|
* You may use, distribute and modify this code under the
|
|
* terms of the private license, which you must obtain from the author
|
|
*
|
|
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
|
|
* real dot sergeych at gmail.
|
|
*/
|
|
|
|
package net.sergeych.crypto2
|
|
|
|
import kotlinx.serialization.Serializable
|
|
import net.sergeych.bipack.BipackDecoder
|
|
import net.sergeych.bipack.BipackEncoder
|
|
import net.sergeych.crypto2.WithFill.Companion.decode
|
|
import net.sergeych.crypto2.WithFill.Companion.encode
|
|
|
|
/**
|
|
* Utility class to optionally extend a message with random bytes added _before the message bytes_ that
|
|
* reduces chances to effective cryptanalysis from the first block. Use
|
|
* [encode] and [decode] to process filled data.
|
|
*/
|
|
@Serializable
|
|
class WithFill private constructor(
|
|
@Suppress("unused")
|
|
val safetyFill: UByteArray = ubyteArrayOf(),
|
|
val data: UByteArray,
|
|
) {
|
|
companion object {
|
|
|
|
/**
|
|
* Create binary data with specified fill
|
|
*/
|
|
fun encode(data: UByteArray,range: IntRange? = null) =
|
|
BipackEncoder.encode(WithFill(range?.let {
|
|
require(range.first >= 0) { "range should not be negative" }
|
|
randomUBytes(randomInt(it))
|
|
} ?: ubyteArrayOf(), data)).toUByteArray()
|
|
|
|
/**
|
|
* extract binary data from filled
|
|
*/
|
|
fun decode(data: UByteArray): UByteArray =
|
|
BipackDecoder.decode<WithFill>(data.asByteArray()).data
|
|
}
|
|
} |