I am trying to find a library to implement password hashing(with salt) using Scrypt algorithm. My question is similar to one already asked in stackoverflow (Hash password in Swift application)
I have found following two libraries in swift and objective c respectively but the hash string generated from these is not matching with the one generated at server.
- Swift-Sodium (https://github.com/jedisct1/swift-sodium)
- NAChloride (https://github.com/gabriel/NAChloride)
Can someone please help in finding library which can be used for Swift 3.0 iOS application for password hashing with salt.
Thank you.
Regards,
Nagraj Wadgire
I had found answer for my own question, thought of sharing as it will be useful for others.
The server team was using Scrypt library (https://github.com/wg/scrypt) to generate hash string for given password and salt.
After analysing the server side library we came to know that the generated hash string contains following components.
1) Scrypt version ($s0$)
2) params (This is calculated using below formula:
String params = Long.toString(log2(N) << 16L | r << 8 | p, 16))
3) Salt in base64 string format
4) Generated derived key in base64 string format
The Format of final hash string is $s0$params$salt$key
(Refer to this question for more information What's the is maximum length of scrypt output?)
As stated in the question I have used NAChloride library at the client side to generate hash string.
This class contains below method for generating hash string:
open class func scrypt(_ password: Data!, salt: Data!, n N: UInt64, r: UInt32, p: UInt32, length: Int) throws -> Data
In our example we have passed below values:
n= 16,
r= 16,
p= 16,
length (bytes) = 32,
salt = Data(bytes:[0x73, 0x61, 0x6c, 0x74, 0x44, 0x61, 0x74, 0x61,0x73, 0x61, 0x6c, 0x74, 0x44, 0x61, 0x74, 0x61,0x73, 0x61, 0x6c, 0x74, 0x44, 0x61, 0x74, 0x61,0x73, 0x61, 0x6c, 0x74, 0x44, 0x61, 0x74, 0x61])
This method will generate only derived key in 'Data' format, thus I was thinking that it is different when compared to the key generated at server side.
I had to write a logic after generating the derived key to match to the format of the hash string (server side hash string format) generated at the server.
Below is the code written in Swift 3.0 to generate hash string for given password using NAChloride library which internally uses Scrypt hash algorithm:
You can also generate the random salt using below method:
Result:
Password: admin1234<
Hash String: $s0$41010$c2FsdERhdGFzYWx0RGF0YXNhbHREYXRhc2FsdERhdGE=$GrMF1P3VH8YrgUEaOJDVSc4as/XTSWhCbbp4DLie00I=