From 76a5e0584de36f6b49a9776deb67d3ded6e61f44 Mon Sep 17 00:00:00 2001 From: JT Olds Date: Mon, 24 Mar 2014 17:26:38 -0600 Subject: [PATCH] space monkey internal commit export [katamari commit: 05c97fb8e733433a63dcedaa7408c63beedd286f] --- engine.go | 39 +++++++++++++++++++++++++++++++++++++++ sha1.go | 20 +++++++++++++++----- 2 files changed, 54 insertions(+), 5 deletions(-) create mode 100644 engine.go diff --git a/engine.go b/engine.go new file mode 100644 index 0000000..bd2029c --- /dev/null +++ b/engine.go @@ -0,0 +1,39 @@ +// Copyright (C) 2014 Space Monkey, Inc. +// +build cgo + +package openssl + +/* +#include "openssl/engine.h" +*/ +import "C" + +import ( + "fmt" + "runtime" + "unsafe" +) + +type Engine struct { + e *C.ENGINE +} + +func EngineById(name string) (*Engine, error) { + cname := C.CString(name) + defer C.free(unsafe.Pointer(cname)) + e := &Engine{ + e: C.ENGINE_by_id(cname), + } + if e.e == nil { + return nil, fmt.Errorf("engine %s missing", name) + } + if C.ENGINE_init(e.e) == 0 { + C.ENGINE_free(e.e) + return nil, fmt.Errorf("engine %s not initialized", name) + } + runtime.SetFinalizer(e, func(e *Engine) { + C.ENGINE_finish(e.e) + C.ENGINE_free(e.e) + }) + return e, nil +} diff --git a/sha1.go b/sha1.go index d88ba4a..4274ca2 100644 --- a/sha1.go +++ b/sha1.go @@ -20,13 +20,16 @@ import ( ) type SHA1Hash struct { - ctx C.EVP_MD_CTX + ctx C.EVP_MD_CTX + engine *Engine } -func NewSHA1Hash() (*SHA1Hash, error) { - hash := new(SHA1Hash) +func NewSHA1Hash() (*SHA1Hash, error) { return NewSHA1HashWithEngine(nil) } + +func NewSHA1HashWithEngine(e *Engine) (*SHA1Hash, error) { + hash := &SHA1Hash{engine: e} C.EVP_MD_CTX_init(&hash.ctx) - runtime.SetFinalizer(hash, func(h *SHA1Hash) { h.Close() }) + runtime.SetFinalizer(hash, func(hash *SHA1Hash) { hash.Close() }) if err := hash.Reset(); err != nil { return nil, err } @@ -37,8 +40,15 @@ func (s *SHA1Hash) Close() { C.EVP_MD_CTX_cleanup(&s.ctx) } +func engineRef(e *Engine) *C.ENGINE { + if e == nil { + return nil + } + return e.e +} + func (s *SHA1Hash) Reset() error { - if 1 != C.EVP_DigestInit_ex(&s.ctx, C.EVP_sha1(), nil) { + if 1 != C.EVP_DigestInit_ex(&s.ctx, C.EVP_sha1(), engineRef(s.engine)) { return errors.New("openssl: sha1: cannot init digest ctx") } return nil