summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorunwox <me@unwox.com>2025-09-04 19:54:05 +0600
committerunwox <me@unwox.com>2025-09-04 19:54:05 +0600
commit3130e934502b733e3be42dff79044c9ded09b30a (patch)
treefe07eacae908e5f57b343ab09dfb11f1fcb5ade8
parent828043e05bff1871f31d9786dbf67c1fc9819f48 (diff)
add password related functions to luna.crypto module
-rw-r--r--main.go60
1 files changed, 58 insertions, 2 deletions
diff --git a/main.go b/main.go
index 35ed343..7939ac9 100644
--- a/main.go
+++ b/main.go
@@ -2,8 +2,8 @@ package main
import (
"bufio"
- "database/sql"
"crypto/sha1"
+ "database/sql"
"encoding/hex"
"errors"
"flag"
@@ -13,18 +13,20 @@ import (
"image/png"
"io"
"log"
+ "math/rand"
"net/http"
"net/url"
"os"
- "unicode/utf8"
"runtime"
"runtime/cgo"
"strings"
"sync"
"time"
+ "unicode/utf8"
_ "github.com/mattn/go-sqlite3"
"github.com/nfnt/resize"
+ "golang.org/x/crypto/bcrypt"
)
var debug bool
@@ -532,6 +534,60 @@ func main() {
io.WriteString(h, str)
return luaOk(l, hex.EncodeToString(h.Sum(nil)))
}
+ cryptoModule["password-hash"] = func (l *Lua) int {
+ var pass string
+ err := l.Scan(&pass)
+ if err != nil {
+ return luaErr(l, err)
+ }
+ saltbuf := make([]byte, 16)
+ rand.Read(saltbuf)
+ salt := hex.EncodeToString(saltbuf)
+ res, err := bcrypt.GenerateFromPassword([]byte(pass+salt), 5)
+ if err != nil {
+ return luaErr(l, err)
+ }
+ return luaOk(l, string(res)+salt)
+ }
+ cryptoModule["passwordHash"] = cryptoModule["password-hash"]
+ cryptoModule["check-password"] = func (l *Lua) int {
+ var pass, hash string
+ err := l.Scan(&pass, &hash)
+ if err != nil {
+ return luaErr(l, err)
+ }
+ hashbytes := []byte(hash)
+ if (len(hashbytes) < 32) {
+ return luaErr(l, errors.New("hash is too short"))
+ }
+ salt := hashbytes[len(hashbytes)-32:]
+ passbytes := []byte(pass+string(salt))
+ hashbytesWithoutSalt := hashbytes[:len(hashbytes)-32]
+ err = bcrypt.CompareHashAndPassword(hashbytesWithoutSalt, passbytes)
+ if err != nil && err != bcrypt.ErrMismatchedHashAndPassword {
+ return luaErr(l, err)
+ }
+ return luaOk(l, err == nil)
+ }
+ cryptoModule["checkPassword"] = cryptoModule["check-password"]
+ cryptoModule["random-string"] = func (l *Lua) int {
+ var length int
+ err := l.Scan(&length)
+ if err != nil {
+ return luaErr(l, err)
+ }
+ if length <= 0 {
+ return luaErr(l, errors.New("length must be positive"))
+ }
+ const charset = "abcdefghijklmnopqrstuvwxyz" +
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ result := make([]byte, length)
+ for i := 0; i < length; i++ {
+ result[i] = charset[rand.Intn(len(charset))]
+ }
+ return luaOk(l, string(result))
+ }
+ cryptoModule["randomString"] = cryptoModule["random-string"]
module := make(map[string]any)
module["router"] = routeModule