gpt4 book ai didi

python - Go 与 Python 的 crypt.crypt 等价的是什么?

转载 作者:IT王子 更新时间:2023-10-29 01:24:19 26 4
gpt4 key购买 nike

我目前正在研究 Violent Python 一书中的一个示例。你可以看到我的实现 here

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

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

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

编辑: Python docs for crypt.crypt

最佳答案

crypt 很容易用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"))
}

运行时产生这个

aaTcvO819w3js

与 python crypt.crypt 相同

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

(已更新以释放 CString - 感谢@james-henstridge)

关于python - Go 与 Python 的 crypt.crypt 等价的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14109915/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com