5

我目前正在玩 Violent Python 一书中的一个例子。你可以在这里看到我的实现

我现在正在尝试在 Go 中实现相同的脚本来比较性能,请注意我对 Go 完全陌生。打开文件并遍历行很好,但是我无法弄清楚如何使用“crypto”库以与 Python 的 crypt.crypt(str_to_hash, salt) 相同的方式对字符串进行哈希处理。我想可能是这样的

import "crypto/des"
des.NewCipher([]byte("abcdefgh"))

但是,没有雪茄。任何帮助将不胜感激,因为将 Go 的并行性能与 Python 的多线程进行比较会非常有趣。

编辑: crypt.crypt 的 Python 文档

4

4 回答 4

3

crypt is very easy to wrap with cgo, eg

package main

import (
    "fmt"
    "unsafe"
)

// #cgo LDFLAGS: -lcrypt
// #define _GNU_SOURCE
// #include <crypt.h>
// #include <stdlib.h>
import "C"

// crypt wraps C library crypt_r
func crypt(key, salt string) string {
    data := C.struct_crypt_data{}
    ckey := C.CString(key)
    csalt := C.CString(salt)
    out := C.GoString(C.crypt_r(ckey, csalt, &data))
    C.free(unsafe.Pointer(ckey))
    C.free(unsafe.Pointer(csalt))
    return out
}

func main() {
    fmt.Println(crypt("abcdefg", "aa"))
}

Which produces this when run

aaTcvO819w3js

Which is identical to python crypt.crypt

>>> from crypt import crypt
>>> crypt("abcdefg","aa")
'aaTcvO819w3js'
>>> 

(Updated to free the CStrings - thanks @james-henstridge)

于 2013-01-01T18:41:00.723 回答
3

我相信目前没有任何公开可用的 Go 包可以实现老式的 Unix“salted”基于 DES 的crypt()功能。这与"crypto/des"包中实现的正常对称 DES 加密/解密不同(正如您所发现的)。

你必须自己实现它。有很多不同语言(主要是 C)的现有实现,例如在FreeBSD 源代码glibc中。如果你在 Go 中实现它,请发布它。:)

对于新项目,最好使用一些更强的密码哈希算法,例如bcryptgo.crypto存储库中提供了一个很好的实现。文档可在此处获得。不幸的是,如果您需要使用预先存在的旧密码哈希,这将无济于事。

编辑添加:我查看了 Python 的crypt.crypt()实现,发现它只是 libc 实现的包装器。为 Go 实现相同的包装器会很简单。但是,您将 Python 实现与 Go 实现进行比较的想法已经破灭:您必须自己实现它们才能进行有意义的比较。

于 2013-01-01T17:59:20.323 回答
2

例如

package main

import (
        "crypto/des"
        "fmt"
        "log"
)

func main() {
        b, err := des.NewCipher([]byte("abcdefgh"))
        if err != nil {
                log.Fatal(err)
        }

        msg := []byte("Hello!?!")
        fmt.Printf("% 02x: %q\n", msg, msg)
        b.Encrypt(msg, msg)
        fmt.Printf("% 02x: %q\n", msg, msg)
        b.Decrypt(msg, msg)
        fmt.Printf("% 02x: %q\n", msg, msg)
}

(另外:http ://play.golang.org/p/czYDRjtWNR )


输出:

48 65 6c 6c 6f 21 3f 21: "Hello!?!"
3e 41 67 99 2d 9a 72 b9: ">Ag\x99-\x9ar\xb9"
48 65 6c 6c 6f 21 3f 21: "Hello!?!"
于 2013-01-01T11:28:52.117 回答
2

好消息!实际上有一个你正在寻找的开源实现。Osutilcrypt有一个在纯 Go中重新实现的 crypt 包。

https://github.com/kless/osutil/tree/master/user/crypt

于 2016-03-25T21:53:01.980 回答