Skip to content

Instantly share code, notes, and snippets.

@ozzpy
Last active March 27, 2019 19:54
Show Gist options
  • Save ozzpy/baaa73697c9170137788dd8951dc0fd3 to your computer and use it in GitHub Desktop.
Save ozzpy/baaa73697c9170137788dd8951dc0fd3 to your computer and use it in GitHub Desktop.
package com.stuff.app.crypto
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import javax.crypto.SecretKey;
class Crypto {
companion object {
const val CRYPTO_ALGO = ""
const val CRYPTO_KEY = ""
const val CRYPTO_CIPHER = ""
}
private val HEX = "0123456789ABCDEF"
private val keyValue = byteArrayOf(
'c'.toByte(),
'o'.toByte(),
'd'.toByte(),
'i'.toByte(),
'n'.toByte(),
'g'.toByte(),
'a'.toByte(),
'f'.toByte(),
'f'.toByte(),
'a'.toByte(),
'i'.toByte(),
'r'.toByte(),
's'.toByte(),
'c'.toByte(),
'o'.toByte(),
'm'.toByte()
)
@Throws(Exception::class)
fun encrypt(cleartext: String): String {
val rawKey: ByteArray = getRawKey()
val result: ByteArray = encrypt(rawKey, cleartext.toByteArray())
return toHex(result)
}
@Throws(Exception::class)
fun decrypt(encrypted: String): String {
val enc: ByteArray = toByte(encrypted)
val result: ByteArray = decrypt(enc)
return String(result)
}
@Throws(Exception::class)
private fun getRawKey(): ByteArray {
val key = SecretKeySpec(keyValue, "AES")
return key.getEncoded()
}
@Throws(Exception::class)
private fun encrypt(raw: ByteArray, clear: ByteArray): ByteArray {
val skeySpec = SecretKeySpec(raw, "AES")
val cipher: Cipher = Cipher.getInstance("AES")
cipher.init(Cipher.ENCRYPT_MODE, skeySpec)
return cipher.doFinal(clear)
}
@Throws(Exception::class)
private fun decrypt(encrypted: ByteArray): ByteArray {
val skeySpec = SecretKeySpec(keyValue, "AES")
val cipher: Cipher = Cipher.getInstance("AES")
cipher.init(Cipher.DECRYPT_MODE, skeySpec)
return cipher.doFinal(encrypted)
}
fun toByte(hexString: String): ByteArray {
val len = hexString.length / 2
val result = ByteArray(len)
for (i in 0 until len)
result[i] = Integer.valueOf(
hexString.substring(2 * i, 2 * i + 2),
16
).toByte()
return result
}
fun toHex(buf: ByteArray?): String {
if (buf == null)
return ""
val result = StringBuffer(2 * buf.size)
for (i in buf.indices) {
appendHex(result, buf[i])
}
return result.toString()
}
/*
* java
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}
*/
private fun appendHex(sb: StringBuffer, b: Byte) {
sb.append(HEX[b shr 4 and 0x0f]).append(HEX[b and 0x0f])
}
}
private infix fun Any.and(i: Int): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
private infix fun Byte.shr(i: Int): Any {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment