英文:
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('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;
}
return salt;
}
function md5(string) {
return crypto.createHash('md5').update(string).digest('hex');
}
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 (
"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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论