Skip to content

Instantly share code, notes, and snippets.

@qwert2603
Created March 9, 2017 09:02
Show Gist options
  • Save qwert2603/66fb47d4f7ef67013cfaf2ba9cb58f5e to your computer and use it in GitHub Desktop.
Save qwert2603/66fb47d4f7ef67013cfaf2ba9cb58f5e to your computer and use it in GitHub Desktop.
fun Int.charsRepeat(c: Char): String = if (this == 0) "" else (1..this).map { c.toString() }.reduce { s1, s2 -> "$s1$s2" }
fun <T> List<T>.reduceToString() = if (isEmpty()) "" else this.map { it.toString() }.reduce { c1, c2 -> "$c1$c2" }
fun powMod(n: Long, p: Long, mod: Long): Long {
var p = p
var res: Long = 1
var pow = n
while (p > 0) {
if (p and 1 == 1L) res = res * pow % mod
pow = pow * pow % mod
p /= 2
}
return res
}
infix fun Long.multiReverse(mod: Long) = (1..mod).first { (it * this) % mod == 1L }
fun encode(m: Long, e: Long, N: Long) = powMod(m, e, N)
fun decode(c: Long, d: Long, N: Long) = powMod(c, d, N)
fun String.charPairs(): List<Pair<Char, Char>> {
val res = mutableListOf<Pair<Char, Char>>()
var char: Char? = null
this.forEach {
char?.apply { res.add(Pair(this, it)) }
char = if (char != null) null else it
}
char?.apply { res.add(Pair(this, 0.toChar())) }
return res
}
fun String.divide(size: Int) = (0..(length + size - 1) / size - 1).map { substring(it * size, minOf((it + 1) * size, length)) }
fun main(args: Array<String>) {
val p: Long = 8627
val q: Long = 9929
val N = p * q
val E: Long = 257
val f = (q - 1) * (p - 1)
val d = E multiReverse f
println("d = $d")
val mess = "message"
println(mess.charPairs())
val c = mess.charPairs()
.map { encode(it.first.toLong().shl(8) + it.second.toLong(), E, N) }
.map { it.toString(16) }
.map { "${(8 - it.length).charsRepeat('0')}$it" }
.reduceToString()
println("c = $c")
val m = c
.divide(8)
.map { it.toLong(16) }
.map { decode(it, d, N) }
.map { listOf(it.shr(8), it.and(0xff)) }
.flatten()
.map(Long::toChar)
.filter { it != 0.toChar() }
.reduceToString()
println("m = $m")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment