javaiosswiftencryptioncryptoswift

Swift equivalent of MessageDigest in Java?


I am trying to do auth encryption in my app, its working for kotlin but not for swift. We are trying to use "AES/ECB/PKCS5Padding". Below kotlin code to get secret key. but my swift code is returning different result then kotlin.

private fun getSecretKey(): SecretKey {
        val messageDigest = MessageDigest.getInstance("SHA-1")
        val key = messageDigest.digest(SECRET_KEY.toByteArray(Charset.forName("UTF-8")))
            .copyOfRange(0, 16)
        return SecretKeySpec(key, "AES")

    }

How can I achieve this in Swift? What is the equivalent of MessageDigest.getInstance in swift.


Solution

  • There is not equivalent of SecretKeySpec. But this Java class mainly wraps a binary key. The below code just returns the binary key data.

    For Swift 4:

        let secretKey = "secret"
        let data = Data(secretKey.utf8)
        var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
        data.withUnsafeBytes { 
            _ = CC_SHA1($0, CC_LONG(data.count), &digest)
        }
        return data