Skip to content

Commit

Permalink
Add pool for sha1 hasher in MySQL
Browse files Browse the repository at this point in the history
  • Loading branch information
ThisGuyCodes committed Dec 25, 2014
1 parent ff997a8 commit fc56475
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 3 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,6 @@ _testmain.go

# Cloud 9
.c9revisions/

# Sublime
*.sublime-workspace
13 changes: 10 additions & 3 deletions Mysql.go → MySQL.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,26 @@
package passwords

import (
"crypto/sha1"
"encoding/hex"
"hash"
)

// Passwords for MySql
func MySQL(pass string) string {
// Create our own hasher, for thread safety
hasher := sha1.New()
// Get our own hasher, for thread safety
hasher := sha1Pool.Get().(hash.Hash)
// Back to the pool! (later)
defer sha1Pool.Put(hasher)

// We cannot assume the hasher from the pool is clean
hasher.Reset()

// This is actually really simple, it's just a sha1 of a sha1 displayed as hex
// (with a leading * to indicate the 'new' password hash of MySql)
hasher.Write([]byte(pass))
interm := hasher.Sum(nil)
hasher.Reset()
hasher.Write(interm)

return "*" + hex.EncodeToString(hasher.Sum(nil))
}
33 changes: 33 additions & 0 deletions MySQL_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package passwords

import (
"testing"
)

const (
mySQLFail = "Password '%s' encrypted by MySQL should have been '%s'; got '%s'."
)

var (
validMySQLPasswords = map[string]string{
"Password1": "*7ee969bbe0a3985c8bff9fa65a06345c67fe434a",
"password": "*2470c0c06dee42fd1618bb99005adca2ec9d1e19",
"recover": "*71383c96a85618165875eb3f9d9e52179c3291e7",
"incorrect": "*2f8bcdbfd7618656393be67f7f1d8ccfaa87f8fc",
}
)

func TestMySQL(t *testing.T) {
for plain, encrypted := range validMySQLPasswords {
got := MySQL(plain)
if encrypted != got {
t.Fatalf(mySQLFail, plain, encrypted, got)
}
}
}

func BenchmarkMySQL(b *testing.B) {
for i := 0; i < b.N; i++ {
MySQL("A slightly longer thing to encrypt")
}
}
9 changes: 9 additions & 0 deletions passwords.sublime-project
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"folders":
[
{
"follow_symlinks": true,
"path": "."
}
]
}
17 changes: 17 additions & 0 deletions pools.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package passwords

import (
"crypto/sha1"
"sync"
)

// This block contains various pools for resources we constantly need; mosty hashers and encoders.
var (
sha1Pool = sync.Pool{
New: sha1New,
}
)

func sha1New() interface{} {
return sha1.New()
}

0 comments on commit fc56475

Please sign in to comment.