Hash password in Swift application

2020-06-27 05:58发布

问题:

For security purposes I will encrypt some data, including the user password in my application.

My colleagues have chosen scrypt hashing algorithm, for a 64 bytes length, with a fixed seed, then converted to hex.

Hashing "A12345678Z" leads to: 25fac84a1cc3a8f6706848d1016cfe7e9d3631691306dcacae68c11c7b54f0bf89e7a7fc51f7fcc19671775acb21c8d928c4c96bb66d915925de58b8b36ab251

Seed is “HeanpyftAkWilfUd”.

On server, they are using this implementation : https://github.com/ricmoo/pyscrypt

Example:

scrypt.hash(“A12345678Z", “HeanpyftAkWilfUd").encode('hex’)

->

25fac84a1cc3a8f6706848d1016cfe7e9d3631691306dcacae68c11c7b54f0bf89e7a7fc51f7fcc19671775acb21c8d928c4c96bb66d915925de58b8b36ab251

My question is how to do that in Swift? What library to use and if it possible - show me sample code, that will lead hashing "A12345678Z" to exactly this:

25fac84a1cc3a8f6706848d1016cfe7e9d3631691306dcacae68c11c7b54f0bf89e7a7fc51f7fcc19671775acb21c8d928c4c96bb66d915925de58b8b36ab251

回答1:

You could use Swift-Sodium. It's a Swift interface for the Sodium crypto library.

Here's an example from the README.md

let sodium = Sodium()!
let password = "Correct Horse Battery Staple".toData()!
let hashedStr = sodium.pwHash.scrypt.str(password,
opsLimit: sodium.pwHash.scrypt.OpsLimitInteractive,
memLimit: sodium.pwHash.scrypt.MemLimitInteractive)!

if sodium.pwHash.scrypt.strVerify(hashStr, passwd: password) == false {
   // Password doesn't match the given hash string
}