将 MD5 从 Node.js 移植到 Go 语言。

huangapple go评论98阅读模式
英文:

Porting MD5 from node.js to go

问题

我有一个在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中?

英文:

I have an authentication logic in node.js

var crypto = require(&#39;crypto&#39;);

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 = &#39;0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ&#39;,
      setLen = set.length,
      salt = &#39;&#39;;
  for (var i = 0; i &lt; len; i++) {
    var p = Math.floor(Math.random() * setLen);
    salt += set

; } return salt; } function md5(string) { return crypto.createHash(&#39;md5&#39;).update(string).digest(&#39;hex&#39;); }

How can I port it to Go?

答案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))
}
英文:

If you only need the standard md5 algorithm, here's how to use it in go, as noted in the documentation:

import (
    &quot;fmt&quot;
    &quot;crypto/md5&quot;
    &quot;io&quot;
)

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

If you need an md5 function that returns a string, here's how to do it:

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

huangapple
  • 本文由 发表于 2013年10月16日 17:39:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/19399964.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定