Monday, January 21, 2013

Calling OpenSSL libcrypto functions from Go

I've released on github three Go packages that present the same set of functions as crypto/md5, crypto/sha1 and crypto/rc4 but that use the OpenSSL libcrypto functions instead of the native Go implementation.

Testing by sending 4.4GB of data through these three functions yields the following results (the test document was the King James Bible concatenated 1,000 times and sent to MD5, SHA1 and RC4 in 4.4MB chunks). All tests were done using go version devel +7dc8d66efb6d Mon Jan 21 10:53:39 2013 +1100 linux/amd64.

MD5SHA1RC4
Native Go404 MB/s123 MB/s111 MB/s
Via OpenSSL607 MB/s636 MB/s744 MB/s
Speedup1.5x5.2x6.7x

These packages provide the same interface as the native Go implementations and should be drop in replacements. libcrypto must be available. The code is available in my go-openssl repository.

PS As this is the first time I've written any cgo code, I'd be happy to hear from more experienced Go programmers about improvements to my wrappers.

PPS As a comparison here is the output of the Go benchmark tests on the native Go implementations of MD5 and SHA1
% go test -bench=".*" crypto/md5
PASS
BenchmarkHash8Bytes          5000000       477 ns/op  16.74 MB/s
BenchmarkHash1K              1000000      2882 ns/op 355.26 MB/s
BenchmarkHash8K               100000     20061 ns/op 408.34 MB/s
BenchmarkHash8BytesUnaligned 5000000       477 ns/op  16.76 MB/s
BenchmarkHash1KUnaligned     1000000      2875 ns/op 356.15 MB/s
BenchmarkHash8KUnaligned      100000     20147 ns/op 406.60 MB/s
ok  crypto/md5 15.997s
% go test -bench=".*" crypto/sha1
PASS
BenchmarkHash8Bytes 2000000       799 ns/op  10.00 MB/s
BenchmarkHash1K      200000      9098 ns/op 112.54 MB/s
BenchmarkHash8K       50000     67341 ns/op 121.65 MB/s
ok  crypto/sha 18.364s
And here's the same with the OpenSSL wrapped versions:
% go test -bench=".*" md5
PASS
BenchmarkHash8Bytes          5000000       611 ns/op  13.09 MB/s
BenchmarkHash1K              1000000      2272 ns/op 450.54 MB/s
BenchmarkHash8K               100000     13816 ns/op 592.92 MB/s
BenchmarkHash8BytesUnaligned 5000000       616 ns/op  12.97 MB/s
BenchmarkHash1KUnaligned     1000000      2282 ns/op 448.59 MB/s
BenchmarkHash8KUnaligned      100000     14089 ns/op 581.44 MB/s
ok  md5 15.049s
% go test -bench=".*" sha1
PASS
BenchmarkHash8Bytes 5000000       625 ns/op  12.78 MB/s
BenchmarkHash1K     1000000      2249 ns/op 455.31 MB/s
BenchmarkHash8K      100000     13507 ns/op 606.46 MB/s
ok  sha1 7.525s

If you enjoyed this blog post, you might enjoy my travel book for people interested in science and technology: The Geek Atlas. Signed copies of The Geek Atlas are available.

<$BlogCommentBody$>

<$BlogCommentDateTime$> <$BlogCommentDeleteIcon$>

Post a Comment

Links to this post:

<$BlogBacklinkControl$> <$BlogBacklinkTitle$> <$BlogBacklinkDeleteIcon$>
<$BlogBacklinkSnippet$>
Create a Link

<< Home