-9

我在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

4

1 回答 1

6

如果您只需要标准md5算法,这里是如何在 go 中使用它,如文档中所述:

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))
}
于 2013-10-16T09:45:49.377 回答