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)
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"
}
}