Files
servicebase/pkg/tools/password.go
2025-11-18 17:48:20 +08:00

108 lines
2.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package tools
import (
"crypto/ecdsa"
"crypto/elliptic"
randcrypto "crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"math/rand"
"time"
)
const (
NUmStr = "0123456789"
CharStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
SpecStr = "+=-@#~,.[]()!%^*$"
)
var (
r = rand.New(rand.NewSource(time.Now().UnixNano()))
)
func GeneratePasswd(level string, length int32) string {
//var (
// length int = 16
// charset = "advance"
//)
//初始化密码切片
var passwd = make([]byte, length, length)
//源字符串
var sourceStr string
//判断字符类型,如果是数字
switch level {
case "num":
sourceStr = NUmStr
case "char":
sourceStr = level
case "mix":
sourceStr = fmt.Sprintf("%s%s", NUmStr, CharStr)
case "advance":
sourceStr = fmt.Sprintf("%s%s%s", NUmStr, CharStr, SpecStr)
default:
sourceStr = NUmStr
}
//遍历生成一个随机index索引,
for i := range passwd {
index := r.Intn(len(sourceStr))
passwd[i] = sourceStr[index]
}
return string(passwd)
}
type PassLevel string
const (
High PassLevel = "advance"
Mid PassLevel = "mix"
Low PassLevel = "char"
Danger PassLevel = "num"
nUmStr = "0123456789"
charStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
specStr = "+=-@#~,.[]()!%^*$"
)
func GeneratePwd(level PassLevel, length int32) string {
var passwd = make([]byte, length, length)
var sourceStr string
switch level {
case Danger:
sourceStr = nUmStr
case Low:
sourceStr = charStr
case Mid:
sourceStr = fmt.Sprintf("%s%s", nUmStr, charStr)
case High:
sourceStr = fmt.Sprintf("%s%s%s", nUmStr, charStr, specStr)
default:
sourceStr = fmt.Sprintf("%s%s", nUmStr, charStr)
}
for i := range passwd {
index := r.Intn(len(sourceStr))
passwd[i] = sourceStr[index]
}
return string(passwd)
}
func GenerateECDSAKeyPem() (primaryKey, publicKey []byte, e error) {
var (
key *ecdsa.PrivateKey
sec []byte
pk []byte
)
if key, e = ecdsa.GenerateKey(elliptic.P256(), randcrypto.Reader); e != nil {
return
}
if sec, e = x509.MarshalECPrivateKey(key); e != nil {
return
}
if pk, e = x509.MarshalPKIXPublicKey(key.Public()); e != nil {
return
}
primaryKey = pem.EncodeToMemory(&pem.Block{Type: "ECD PRIVATE KEY", Bytes: sec})
publicKey = pem.EncodeToMemory(&pem.Block{Type: "ECD PUBLIC KEY", Bytes: pk})
return
}