Last active
December 29, 2023 21:07
-
-
Save shank03/82f8f1a217dd3a707a97c4b59866f446 to your computer and use it in GitHub Desktop.
A simple XOR cipher/encryption in kotlin :)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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 | |
} | |
} |
Author
shank03
commented
Sep 22, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment