Skip to content

Instantly share code, notes, and snippets.

@shank03
Last active December 29, 2023 21:07
Show Gist options
  • Save shank03/82f8f1a217dd3a707a97c4b59866f446 to your computer and use it in GitHub Desktop.
Save shank03/82f8f1a217dd3a707a97c4b59866f446 to your computer and use it in GitHub Desktop.
A simple XOR cipher/encryption in kotlin :)
/*
* Copyright (c) 2020, Shashank Verma <shashank.verma2002@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
/**
* @author Shashank Verma
*
* XOR Cipher.
* It can only decrypt with right keys ;)
*/
object XORCryptor {
private fun generateMask(value: Int): Int {
var mask = 0
var prV = value
while (prV != 0) {
if (prV and 1 == 1) mask++
prV = prV shr 1
}
mask = mask or ((8 - mask) shl 4)
mask = mask xor ((mask shl 4) or (mask shr 4))
return mask xor value
}
fun processBytes(srcBytes: ByteArray, keyBytes: ByteArray): ByteArray {
var keyIdx = 0
for (i in srcBytes.indices) {
if (keyIdx == keyBytes.size) keyIdx = 0
val b = srcBytes[i].toInt()
val k = generateMask(keyBytes[keyIdx++].toInt())
srcBytes[i] = b.xor(k).toByte()
}
return srcBytes
}
}
@shank03
Copy link
Author

shank03 commented Sep 22, 2022

// Usage:

fun main() {
    print("Enter text: ")
    val text = readLine()!!
    print("Enter key: ")
    val key = readLine()!!

    var data = String(XORCryptor.processBytes(text.toByteArray(), key.toByteArray()))
    println("Encrypted: $data")

    data = String(XORCryptor.processBytes(data.toByteArray(), key.toByteArray()))
    println("Decrypted: $data")
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment