Last active
June 12, 2020 09:11
-
-
Save roodkcab/b1f92a2a57d58076957db8e25d579602 to your computer and use it in GitHub Desktop.
EVP_BytesToKey swif3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| func evpBytesToKey(password:String, keyLen:Int, ivLen:Int) -> ([UInt8], [UInt8]) { | |
| var m = [Data]() | |
| guard let passwd = password.data(using: String.Encoding.utf8) else { | |
| return ([], []); | |
| } | |
| while m.reduce(0, {$0 + $1.count}) < keyLen + ivLen { | |
| let data = m.count > 0 ? m.last! + passwd : passwd | |
| m.append(data.md5Digest()) | |
| } | |
| let final = m.reduce(Data(), +) | |
| return (Array(final.bytes[0...(keyLen - 1)]), Array(final.bytes[keyLen...(keyLen + ivLen - 1)])) | |
| } | |
| /*def EVP_BytesToKey(password, key_len, iv_len): | |
| # equivalent to OpenSSL's EVP_BytesToKey() with count 1 | |
| # so that we make the same key and iv as nodejs version | |
| password = str(password) | |
| m = [] | |
| i = 0 | |
| while len(''.join(m)) < (key_len + iv_len): | |
| md5 = hashlib.md5() | |
| data = password | |
| if i > 0: | |
| data = m[i - 1] + password | |
| md5.update(data) | |
| m.append(md5.digest()) | |
| i += 1 | |
| ms = ''.join(m) | |
| key = ms[:key_len] | |
| iv = ms[key_len:key_len + iv_len] | |
| return (key, iv)*/ |
Thanks for your your job!
Could you please give a piece of advice: what to do if we have salt too?
How to refactor the algo to include salt?
Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What is data.md5Digest()?