0

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.

  • 2
    “my swift code is returning different result” – I can see no Swift code in your question. – Martin R Jul 12 '19 at 07:09
  • 2
    Note that this Kotlin code shows terrible cryptgraphic practices. Taking a normal cryptographic hash over a password does not make a secure key. You'd need a Password Based Key Derivation Function or PBKDF for that. Java has PBKDF2 in the default JRE by Oracle. So you should replace the code above altogether instead of copying it. – Maarten Bodewes Jul 12 '19 at 09:15
  • @MartinR He did that in his previous question, he just reposted the partial question when he didn't get a quick answer :( – Maarten Bodewes Jul 12 '19 at 09:20

1 Answers1

1

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
Codo
  • 75,595
  • 17
  • 168
  • 206