dongzhi1904 2013-10-16 09:39
浏览 44
已采纳

从node.js移植MD5去[关闭]

I have an authentication logic in 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');
}

How can I port it to Go?

  • 写回答

1条回答 默认 最新

  • doubingling4706 2013-10-16 09:45
    关注

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

    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))
    }
    

    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("%x", h.Sum(nil))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含