问题描述
我目前正在玩暴力Python一书中的一个例子。您可以在
crypt
是非常容易用cgo包装,例如
包主
导入(
fmt
unsafe
)
// #cgo LDFLAGS:-lcrypt
// #define _GNU_SOURCE
// #include< crypt。 h取代;
//#包括< stdlib.h>
导入C
// crypt封装C库crypt_r
func crypt(键,盐串)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))
返回
}
func main (){
fmt.Println(crypt(abcdefg,aa))
}
运行时产生此结果
aaTcvO819w3js
这与python crypt.crypt
>>> from crypt import crypt
>>> crypt(abcdefg,aa)
'aaTcvO819w3js'
>>>
(更新为释放CStrings - thanks @ james-henstridge)
I am currently playing around with an example from the book Violent Python. You can see my implementation here
I am now trying to implement the same script in Go to compare performance, note I am completely new to Go. Opening the file and iterating over the lines is fine, however I cannot figure out how to use the "crypto" library to hash the string in the same way as Python's crypt.crypt(str_to_hash, salt). I thought it maybe something like
import "crypto/des"
des.NewCipher([]byte("abcdefgh"))
However, no cigar. Any help would be much appreciated as it'd be really interesting to compare Go's parallel performance to Python's multithreaded.
Edit:Python docs for crypt.crypt
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)
这篇关于Go与Python的crypt.crypt等价吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!