How to decrypt a string in DES decrypt?

163 Views Asked by At

Trying this method to encrypt and decrypt. That work encrypt string successfully but can't do decrypt successfully. I use encrypt method if operation value is "E" and else it should do decrypt. I just tried these code inside else there. I doesn't decrypt true. How can do this?

Using Method:

val encryptedCardId = doCipher(result.data.cardId, result.data.ci360, "E")
val decryptedCardId = doCipher(encryptedCardId, result.data.ci360, "D")

Method:

 fun doCipher(plainText: String, ci: String, operation: String): String? {
                /* * Service new Key **/
                val key = ci.substring(0,24)
                val initializationVector = ci.takeLast(8)
                var password: String? = null
                var myKey: SecretKeySpec? = null
                val plaintext = plainText.toByteArray()
                val tdesKeyData = key.toByteArray()
                val myIV = initializationVector.toByteArray()
                val c3des: Cipher
                try {
                    c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding")
                    myKey = SecretKeySpec(tdesKeyData, "DESede")
                    var ivspec: IvParameterSpec? = null
                    try {
                        ivspec = IvParameterSpec(myIV)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    if (operation == "E") {
                        c3des.init(Cipher.ENCRYPT_MODE, myKey, ivspec)
                        val cipherText = c3des.doFinal(plaintext)
                        password = Base64.encodeToString(cipherText, Base64.DEFAULT)
                    } else {
                        c3des.init(Cipher.DECRYPT_MODE, myKey, ivspec)
                        val cipherText = c3des.doFinal(Base64.decode(plaintext, Base64.DEFAULT))
                        password = cipherText.toString()
                    }
        
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                return password
            }
1

There are 1 best solutions below

2
XaMi On

Use this Method for Decrypt

fun Decrypt(text: String, key: String): String {
    val cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding")
    val keyBytes = ByteArray(16)
    val b = key.toByteArray(charset("UTF-8"))
    var len = b.size
    if (len > keyBytes.size) len = keyBytes.size
    System.arraycopy(b, 0, keyBytes, 0, len)
    val keySpec = SecretKeySpec(keyBytes, "DESede")
    val ivSpec = IvParameterSpec(keyBytes)
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec)
    var results: ByteArray? = ByteArray(text.length)
    try {
        results = cipher.doFinal(Base64.decode(text, 0))
    } catch (e: Exception) {
        Log.i("Erron in Decryption", e.toString())
    }
    Log.i("Data", String(results!!))
    return String(results) // it returns the result as a String
}