Search code examples
swiftkotlinencryptionrsasha512

Swift Sha512 Encryption ( translate Kotlin code )


This is the Kotlin code:

private fun verify(inputDataToVerify: String, signature: String): Boolean {
    return try {
        val pubKey = "XXXMYPUBKEYXXX"
        val bytesFromPropFile = pubKey.toByteArray()
        val keySpec = X509EncodedKeySpec(Base64.decode(bytesFromPropFile, Base64.DEFAULT))
        val keyFactory = KeyFactory.getInstance("RSA")
        val publicKey = keyFactory.generatePublic(keySpec)
        Signature.getInstance("SHA512WithRSA").run {
            initVerify(publicKey)
            update(inputDataToVerify.toByteArray())
            verify(Base64.decode(signature.toByteArray(), Base64.DEFAULT))
        }
    } catch (ex: Exception) {
        Timber.e(ex)
        false
    }
}

I have to convert this piece of code to Swift because I need the same behavior in my iOS app but I'm really new to encryption. How can I do? I need third part library?


Solution

  • i found a solution with SwiftyRSA, that's the method

    private func verifySignature(inputDataToVerify: String, signature: String) -> Bool{
        
        let pubKeyString = environmentService.getNexiPubKey()
        
        do {
            let publicKey = try PublicKey(pemEncoded: pubKeyString)
            let clear = try ClearMessage(string: inputDataToVerify, using: .utf8)
            let sign = try Signature(base64Encoded: signature)
            let isSuccessfull = try clear.verify(with: publicKey, signature: sign, digestType: .sha512)
            
            return isSuccessfull
        }
        catch let error{
            print(error)
            return false
        }
    
    }