【问题标题】:aes encryption not working in android studio using kotlin?(EDITED)aes 加密在使用 kotlin 的 android studio 中不起作用?(已编辑)
【发布时间】:2021-07-12 07:43:12
【问题描述】:

我的代码
,,,

     //key genration
    val keygen = KeyGenerator.getInstance("AES")
    keygen.init(256)
    val key = keygen.generateKey()
    keyTV.setText(key.toString())

    val encoder = Base64.getEncoder()
    val decoder = Base64.getDecoder()

    encryptbtn.setOnClickListener(View.OnClickListener {
        val plaintext = message.text.toString()

        // object of cipher
        val cipher = Cipher.getInstance("AES")
        cipher.init(Cipher.ENCRYPT_MODE,key)

        // encrypted message
        val ciphertext = cipher.doFinal(plaintext.toByteArray(Charsets.UTF_8))


        encryptMsgTV.setText(String(encoder.encode(ciphertext)))
    })

    decryptbtn.setOnClickListener(View.OnClickListener {
        val str = encryptMsgTV.text.toString()
        val ciphertext = decoder.decode(str.toByteArray(Charsets.UTF_8))

        val decipher = Cipher.getInstance("AES")
        decipher.init(Cipher.DECRYPT_MODE,key)

        val plaintext = decipher.doFinal(ciphertext)
        decryptMsgTV.setText(plaintext.toString())
    })

,,,

错误:- 现在我更新了我的代码,但现在所有错误都解决了,但我的解密出了点问题,它没有正确解密

【问题讨论】:

  • 您的问题是您将 AES 加密的结果视为有效字符串的编码,但事实并非如此,它只是一个任意字节序列。那就是ciphertext.toString() 没有意义,实际上会破坏数据。

标签: android kotlin encryption cryptography aes


【解决方案1】:

这是我的解决方案 实现 'commons-codec:commons-codec:1.11'

private fun decrypt(plainText: String): String? {
        val cipher = Cipher.getInstance("AES/ECB/NoPadding")
        val key: SecretKey = SecretKeySpec(hexToByteArray(keyHex), "AES")
        cipher.init(Cipher.DECRYPT_MODE, key)
        val result = cipher.update(hexToByteArray(plainText))
        val text = String(Hex.encodeHex(result))
        val finalText = String(hexToByteArray(text)!!)
        return finalText.trim { it <= ' ' }
    }

    fun hexToByteArray(s: String?): ByteArray? {
        require(!(s == null || s.length % 2 == 1))
        val chars = s.toCharArray()
        val len = chars.size
        val data = ByteArray(len / 2)
        var i = 0
        while (i < len) {
            data[i / 2] =
                ((Character.digit(chars[i], 16) shl 4) + Character.digit(
                    chars[i + 1],
                    16
                )).toByte()
            i += 2
        }
        return data
    }

【讨论】:

  • 什么是keyHex和Hex变量?
猜你喜欢
  • 2014-08-20
  • 1970-01-01
  • 1970-01-01
  • 2017-09-26
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 2021-12-30
  • 1970-01-01
相关资源
最近更新 更多