-
-
Save krkhan/f8b42bad4350bb708a56040fd489f120 to your computer and use it in GitHub Desktop.
Incremental golang md5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
/* | |
#cgo pkg-config: openssl | |
#include <openssl/md5.h> | |
*/ | |
import "C" | |
import ( | |
"encoding/hex" | |
"errors" | |
"fmt" | |
"unsafe" | |
) | |
type MD5Context C.MD5_CTX | |
func MD5New() (*MD5Context, error) { | |
var ctx MD5Context | |
ret := C.MD5_Init((*C.struct_MD5state_st)(&ctx)) | |
if ret == 0 { | |
return nil, errors.New("Error during MD5 init") | |
} | |
return &ctx, nil | |
} | |
func (ctx *MD5Context) Update(data []byte) error { | |
if len(data) == 0 { | |
return nil | |
} | |
ret := C.MD5_Update((*C.struct_MD5state_st)(ctx), unsafe.Pointer(&data[0]), C.size_t(len(data))) | |
if ret == 0 { | |
return errors.New("Error during MD5 update") | |
} | |
return nil | |
} | |
func (ctx *MD5Context) Final() ([]byte, error) { | |
res := make([]byte, C.MD5_DIGEST_LENGTH) | |
ret := C.MD5_Final((*C.uchar)(unsafe.Pointer(&res[0])), (*C.struct_MD5state_st)(ctx)) | |
if ret == 0 { | |
return res, errors.New("Error during MD5 finalize") | |
} | |
return res, nil | |
} | |
func main() { | |
m5, _ := MD5New() | |
m5.Update([]byte("secretdata")) | |
sum, _ := m5.Final() | |
fmt.Printf("sum: %s\n", hex.EncodeToString(sum)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment