1 year ago

#71998

test-img

Fawwaz Ali

RSA Decrytion Fail in Android

I am facing some problem in decryption RSA in android Using Kotlin I dont know what is going wrong , Need some Help Error Reads As input should be less than 128bytes and its occurring in decryption Function

Code -

        val keyGen = KeyPairGenerator.getInstance("RSA")
        keyGen.initialize(1024)
        val keyPair = keyGen.generateKeyPair()
        val privateKey = keyPair.private
        val publicKey = keyPair.public
        val encoder: java.util.Base64.Encoder = java.util.Base64.getEncoder()
        val m = encoder.encodeToString(privateKey.encoded)
        val l = encoder.encodeToString(publicKey.encoded)
        Log.d("keys","$m andddddddddddddd  $l")
        val xyz = "abcdefgh"
        fun encryption(data: String): String {
            var encoded = ""
            var encrypted: ByteArray? = null
            val publicBytes: ByteArray? = Base64.decode(l, Base64.DEFAULT)
            val keySpec: java.security.spec.X509EncodedKeySpec = java.security.spec.X509EncodedKeySpec(publicBytes)
            val keyFactory = KeyFactory.getInstance("RSA")
            val pubKey = keyFactory.generatePublic(keySpec)
            val cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING")
            cipher.init(Cipher.ENCRYPT_MODE, pubKey)
            encrypted = cipher.doFinal(data.toByteArray())
            Log.d("test","$encrypted")
            encoded = Base64.encodeToString(encrypted, Base64.DEFAULT)
            Log.d("final", encoded)
            return encoded
        }
        val o = encryption(xyz)
        val nom = o.length
        Log.d("leng","$nom")
        fun decryption(data: String) : String{

            var decoded = ""
            var decrypted: ByteArray? = null
            val privateBytes: ByteArray? = Base64.decode(m, Base64.DEFAULT)
            val keySpec:PKCS8EncodedKeySpec = PKCS8EncodedKeySpec(privateBytes)
            val keyFactory = KeyFactory.getInstance("RSA")
            val prvKey = keyFactory.generatePrivate(keySpec)
            val cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING")
            cipher.init(Cipher.DECRYPT_MODE, prvKey)
            decrypted = cipher.doFinal(o.toByteArray())
            decoded = Base64.encodeToString(decrypted, Base64.DEFAULT)
            Log.d("finald", "$decoded")
            return decoded

        }

        decryption(o)

android

android-studio

kotlin

rsa

0 Answers

Your Answer

Accepted video resources