将MD5从node.js移植到go

时间:2013-10-16 09:39:41

标签: javascript node.js authentication go md5

我在node.js

中有一个身份验证逻辑
var crypto = require('crypto');

var SaltLength = 9;

function createHash(password) {
  var salt = generateSalt(SaltLength);
  var hash = md5(password + salt);
  return salt + hash;
}

function validateHash(hash, password) {
  var salt = hash.substr(0, SaltLength);
  var validHash = salt + md5(password + salt);
  return hash === validHash;
}

function generateSalt(len) {
  var set = '0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ',
      setLen = set.length,
      salt = '';
  for (var i = 0; i < len; i++) {
    var p = Math.floor(Math.random() * setLen);
    salt += set[p];
  }
  return salt;
}

function md5(string) {
  return crypto.createHash('md5').update(string).digest('hex');
}

如何将其移植到Go

1 个答案:

答案 0 :(得分:6)

如果您只需要标准的md5算法,请按照以下documentation中的说明使用,如{{3}}中所述:

import (
    "fmt"
    "crypto/md5"
    "io"
)

func main() {
    h := md5.New()
    io.WriteString(h, "The fog is getting thicker!")
    io.WriteString(h, "And Leon's getting laaarger!")
    fmt.Printf("%x", h.Sum(nil))
}

如果您需要一个返回字符串的md5函数,请按以下步骤操作:

func md5(input string) string {
    h := md5.New()
    io.WriteString(h, input)
    return fmt.Sprintf("%x", h.Sum(nil))
}