【问题标题】:Hash function with Glibc使用 Glibc 的哈希函数
【发布时间】:2017-09-01 17:12:29
【问题描述】:

我一直在尝试在 Swift 中加密字符串,但是我希望它能够在 linux 下工作。类似以下代码的答案(取自 these questions 不起作用,因为它们依赖于 iOS 或 OSx 库:

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 来做到这一点?

【问题讨论】:

    标签: swift linux glibc


    【解决方案1】:

    glibc 中有一个 crypt 库,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

    【讨论】:

      猜你喜欢
      • 2023-03-21
      • 2012-05-09
      • 1970-01-01
      • 2016-03-25
      • 2011-02-27
      • 2017-08-10
      • 2015-01-26
      • 2012-06-04
      • 1970-01-01
      相关资源
      最近更新 更多