2017-09-01 131 views
2

我一直在試圖在Swift中加密字符串,但是我希望它能在linux下工作。如下面的代碼(從thesequestions採取的答案是不行的,因爲它們依賴無論是在iOS和OSX庫:與Glibc的哈希函數

func sha256(data : Data) -> Data { 
    var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) 
    data.withUnsafeBytes { 
     _ = CC_SHA256($0, CC_LONG(data.count), &hash) 
    } 
    return Data(bytes: hash) 
} 
  • 那怎麼可以在Linux中使用的Glibc做

回答

1

有在glibc的土窖庫,see manpage
您需要包括:。#include <crypt.h>

你必須要使用的功能是:

char *crypt(const char *key, const char *salt); 

根據該手冊頁的SHA-256算法,因爲Glibc 2.7集成並經由salt參數被選擇:

The glibc2 version of this function supports additional encryption 
algorithms. 

If salt is a character string starting with the characters "$id$" 
followed by a string terminated by "$": 

     $id$salt$encrypted 

then instead of using the DES machine, id identifies the encryption 
method used and this then determines how the rest of the password 
string is interpreted. The following values of id are supported: 

     ID | Method 
     ───────────────────────────────────────────────────────── 
     1 | MD5 
     2a | Blowfish (not in mainline glibc; added in some 
      | Linux distributions) 
     5 | SHA-256 (since glibc 2.7) 
     6 | SHA-512 (since glibc 2.7) 

So $5$salt$encrypted is an SHA-256 encoded password and 
$6$salt$encrypted is an SHA-512 encoded one. 

"salt" stands for the up to 16 characters following "$id$" in the 
salt. The encrypted part of the password string is the actual 
computed password. The size of this string is fixed: 

MD5  | 22 characters 
SHA-256 | 43 characters 
SHA-512 | 86 characters 

The characters in "salt" and "encrypted" are drawn from the set 
[a-zA-Z0-9./]. In the MD5 and SHA implementations the entire key is 
significant (instead of only the first 8 bytes in DES). 

this official GNU pagethis wikipedia article是解釋和例子:

SHA-256的參數示例salt
$5$9ks3nNEqv31FX.F$gdEoLFsCRsn/WRN3wxUnzfeZLoooVlzeF4WjLomTRFD