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?
CodePudding user response:
You don't need to encrypt anything, you need to verify a signature. The algorithms are:
SubjectPublicKeyInfo
orspki
for the public key (as defined in the X509 certificate standards, hence the name);- The old RSA / PKCS#1 signature verification algorithm (obviously with SHA-512 as hash algorithm).
Note that toByteArray()
encodes a string to binary using UTF-8 as default. Obviously it should not really be needed before base 64 decoding, but yeah...
CodePudding user response:
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
}
}