Search code examples
pythongodescrypt

What is Go's equivalent to Python's crypt.crypt?


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


Solution

  • 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)