Skip to content

Instantly share code, notes, and snippets.

@DuckSoft
Last active October 5, 2018 22:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DuckSoft/92a4944f94314affe816eeb1bf80b63b to your computer and use it in GitHub Desktop.
Save DuckSoft/92a4944f94314affe816eeb1bf80b63b to your computer and use it in GitHub Desktop.
Kotlin DES+Base64 Snipplet

Code

import java.util.*
import javax.crypto.Cipher
import javax.crypto.SecretKey

fun ByteArray.encryptDES(key: SecretKey): ByteArray? = try {
    Cipher.getInstance("DES")?.run {
        init(Cipher.ENCRYPT_MODE, key)
        doFinal(this@encryptDES)
    }
} catch (e: Exception) {
    null
}

fun ByteArray.decryptDES(key: SecretKey): ByteArray? = try {
    Cipher.getInstance("DES")?.run {
        init(Cipher.DECRYPT_MODE, key)
        doFinal(this@decryptDES)
    }
} catch (e: Exception) {
    null
}

fun ByteArray.toBase64(): ByteArray = Base64.getEncoder().encode(this)
fun ByteArray.toBase64String(): String = toBase64().toRealString()
fun ByteArray.fromBase64(): ByteArray? = Base64.getDecoder().decode(this)


fun String.decryptBase64DES(key: SecretKey): String? = toByteArray().fromBase64()?.decryptDES(key)?.toRealString()
fun String.encryptBase64DES(key: SecretKey): String? = toByteArray().encryptDES(key)?.toBase64String()
fun ByteArray.toRealString(): String = String(this)

fun String.decryptBase64DES(key: SecretKey): String? = toByteArray().fromBase64()?.decryptDES(key)?.toRealString()
fun String.encryptBase64DES(key: SecretKey): String? = toByteArray().encryptDES(key)?.toBase64String()
fun ByteArray.toRealString(): String = String(this)

Test

import io.kotlintest.shouldBe
import io.kotlintest.specs.StringSpec

class EncryptionExtensionKtTest : StringSpec({
    "DES-Base64 encryption test" {
        "this-is-something-to-encrypt".encryptBase64DES(
                "this-is-test-key-text".toDESKey()
        ) shouldBe "YHX0KrpeoF6+5QY6w9bt8qn03dZgmDwe2odggfXO0Q4="
    }

    "DES-Base64 decryption test" {
        "YHX0KrpeoF6+5QY6w9bt8qn03dZgmDwe2odggfXO0Q4=".decryptBase64DES(
                "this-is-test-key-text".toDESKey()
        ) shouldBe "this-is-something-to-encrypt"
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment