search
HomeBackend DevelopmentGolangLet&#s build a password generator we can actually use

For our next beginner project, we will build a password generator that doesn't only generate passwords but encrypts and saves them - so that it is actually functional.

We will be splitting our code into different files so we don't end up with a large "main.go" file.

First, we initialize a go project and create a "profile.go" file that will contain the logic for encrypting and decrypting passwords.

package main

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "encoding/hex"
    "errors"
    "io"
)

// must be 32 characters 
var key = "askdjasjdbreonfsdfibsdhfgsdfhboo"

var ErrMalformedEncryption = errors.New("malformed encryption")

// password in small letters so it is not stored
type profile struct {
    Enc, Platform, password string
}

func (p *profile) encrypt() error {
    block, err := aes.NewCipher([]byte(key))
    if err != nil {
        return err
    }

    gcm, err := cipher.NewGCM(block)
    if err != nil {
        return err
    }

    nonce := make([]byte, gcm.NonceSize())

    if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
        return err
    }

    enc := gcm.Seal(nonce, nonce, []byte(p.password), nil)
    p.Enc = hex.EncodeToString(enc)

    return nil
}

func (p *profile) decrypt() error {
    block, err := aes.NewCipher([]byte(key))
    if err != nil {
        return err
    }

    gcm, err := cipher.NewGCM(block)
    if err != nil {
        return err
    }

    nsize := gcm.NonceSize()

    if len(p.Enc) 



<p>Here we create a profile struct that has 3 fields - Enc, Platform and password. Enc will hold the encrypted password, the service we are generating the password for will be stored in Platform and password will hold the actual generated password. The profile struct has 2 methods "encrypt" and "decrypt". We use AES - a symmetric key encryption algorithm to encrypt and decrypt our password. </p>

<p>Next we create a "store.go" file that contains the logic for storing and retrieving passwords.<br>
</p>

<pre class="brush:php;toolbar:false">package main

import (
    "encoding/gob"
    "errors"
    "os"
    "sync"
)

const filename = "profile.bin"

var (
    ErrInvalidArgs = errors.New("invalid args")
    ErrNotFound    = errors.New("not found")
)

type store struct {
    sync.RWMutex
    data map[string]*profile
}

func newStore() (*store, error) {
    s := &store{
        data: make(map[string]*profile),
    }

    if err := s.load(); err != nil {
        return nil, err
    }

    return s, nil
}

func (s *store) load() error {
    flags := os.O_CREATE | os.O_RDONLY
    f, err := os.OpenFile(filename, flags, 0644)
    if err != nil {
        return err
    }
    defer f.Close()

    info, err := f.Stat()
    if err != nil {
        return err
    }

    if info.Size() == 0 {
        return nil
    }

    return gob.NewDecoder(f).Decode(&s.data)
}

func (s *store) save() error {
    f, err := os.OpenFile(filename, os.O_WRONLY, 0644)
    if err != nil {
        return err
    }
    defer f.Close()

    return gob.NewEncoder(f).Encode(s.data)
}

func (s *store) find(platform string) (string, error) {
    s.RLock()
    defer s.RUnlock()

    p, ok := s.data[platform]
    if !ok {
        return "", ErrNotFound
    }

    if err := p.decrypt(); err != nil {
        return "", err
    }

    return p.password, nil
}

func (s *store) add(platform, password string) error {
    if platform == "" {
        return ErrInvalidArgs
    }

    p := &profile{
        Platform: platform,
        password: password,
    }

    if err := p.encrypt(); err != nil {
        return err
    }

    s.Lock()
    defer s.Unlock()

    s.data[platform] = p

    return s.save()
}

We chose gob files for storage because they are not exactly human readable. If the file ever gets exposed, your passwords are safe because they will be encrypted and really difficult to read. The store struct contains methods for loading, finding and saving to the gob file. We save the passwords in a dictionary. We also use a mutex to make the dictionary concurrent safe. An important thing to note is that we will not be storing the plain generated password - we will store its encrypted value instead.

Now let's write a couple of functions that will actually generate the passwords. Create a "password.go" file and type the following

package main

import (
    "math"
    "math/rand"
    "slices"
    "strings"
)

const (
    half      = .5
    onethird  = .3
    onefourth = .25
)

var (
    randlowers  = randFromSeed(lowers())
    randuppers  = randFromSeed(uppers())
    randdigits  = randFromSeed(digits())
    randsymbols = randFromSeed(symbols())
)

var basicPassword = randlowers

func mediumPassword(n int) string {
    frac := math.Round(float64(n) * half)
    pwd := basicPassword(n)
    return pwd[:n-int(frac)] + randuppers(int(frac))
}

func hardPassword(n int) string {
    pwd := mediumPassword(n)
    frac := math.Round(float64(n) * onethird)
    return pwd[:n-int(frac)] + randdigits(int(frac))
}

func xhardPassword(n int) string {
    pwd := hardPassword(n)
    frac := math.Round(float64(n) * onefourth)
    return pwd[:n-int(frac)] + randsymbols(int(frac))
}

func randFromSeed(seed string) func(int) string {
    return func(n int) string {
        var b strings.Builder
        for range n {
            b.WriteByte(seed[rand.Intn(len(seed))])
        }
        return b.String()
    }
}

func lowers() string {
    var b strings.Builder
    for i := 'a'; i 



<p>Here we've written functions that generates passwords at different levels of difficulty. The basicPassword function generates random small letter strings. The mediumPassword function takes a fraction of the characters from basicPassword function and adds random capital letters to it. The hardPassword function does the same for mediumPassword but adds digits to it. The xhardPassword does the same and adds symbols. The shuffle function does exactly what you'd expect on slices while shuffleStr shuffles strings.</p>

<p>Now let's put everything together. Create a "main.go" file and type the following<br>
</p>

<pre class="brush:php;toolbar:false">package main

import (
    "errors"
    "flag"
    "fmt"
    "log"
    "regexp"
    "strconv"
    "strings"
)

var usage = `
Usage 
-----
--get platform=[string] - Gets saved password for a platform
--set platform=[string] len=[int] level=(basic|medium|hard|xhard) - Creates and saves a password
`

var ErrUsage = errors.New(usage)

var pattern = regexp.MustCompile(`\S+=\S+`)

type level int

const (
    _ level = iota
    level_basic
    level_medium
    level_hard
    level_xhard
)

var level_key = map[string]level{
    "basic":  level_basic,
    "medium": level_medium,
    "hard":   level_hard,
    "xhard":  level_xhard,
}

type commands struct {
    get, set bool
}

func createCommands() (c commands) {
    flag.BoolVar(&c.get, "get", false, "get password for platform")
    flag.BoolVar(&c.set, "set", false, "set password for platform")
    flag.Parse()
    return
}

func (c commands) exec(store *store) (string, error) {
    switch {
    case c.get:
        return c.getPassword(store)
    case c.set:
        return c.setPassword(store)
    default:
        return "", ErrUsage
    }
}

func (c commands) getPassword(store *store) (string, error) {
    params, err := c.parse()
    if err != nil {
        return "", err
    }

    return store.find(params["platform"])
}

func (c commands) setPassword(store *store) (string, error) {
    params, err := c.parse()
    if err != nil {
        return "", err
    }

    var password string

    n, err := strconv.Atoi(params["len"])
    if err != nil {
        return "", err
    }

    if n 



<p>We used flags to specify how we expect the application to behave. "--get" to get a password and "--set" to generate and save a password. To set a password, the user provides arguments with the flags to instruct the application on the type of password to generate and save. To get a password, the user also provides arguments to specify the password to retrieve.</p>

<p>You can now run "go build" to build a binary and test the application.</p>

<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173158638678335.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Let"></p>


          

            
        

The above is the detailed content of Let&#s build a password generator we can actually use. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
String Manipulation in Go: Mastering the 'strings' PackageString Manipulation in Go: Mastering the 'strings' PackageMay 14, 2025 am 12:19 AM

Mastering the strings package in Go language can improve text processing capabilities and development efficiency. 1) Use the Contains function to check substrings, 2) Use the Index function to find the substring position, 3) Join function efficiently splice string slices, 4) Replace function to replace substrings. Be careful to avoid common errors, such as not checking for empty strings and large string operation performance issues.

Go 'strings' package tips and tricksGo 'strings' package tips and tricksMay 14, 2025 am 12:18 AM

You should care about the strings package in Go because it simplifies string manipulation and makes the code clearer and more efficient. 1) Use strings.Join to efficiently splice strings; 2) Use strings.Fields to divide strings by blank characters; 3) Find substring positions through strings.Index and strings.LastIndex; 4) Use strings.ReplaceAll to replace strings; 5) Use strings.Builder to efficiently splice strings; 6) Always verify input to avoid unexpected results.

'strings' Package in Go: Your Go-To for String Operations'strings' Package in Go: Your Go-To for String OperationsMay 14, 2025 am 12:17 AM

ThestringspackageinGoisessentialforefficientstringmanipulation.1)Itofferssimpleyetpowerfulfunctionsfortaskslikecheckingsubstringsandjoiningstrings.2)IthandlesUnicodewell,withfunctionslikestrings.Fieldsforwhitespace-separatedvalues.3)Forperformance,st

Go bytes package vs strings package: Which should I use?Go bytes package vs strings package: Which should I use?May 14, 2025 am 12:12 AM

WhendecidingbetweenGo'sbytespackageandstringspackage,usebytes.Bufferforbinarydataandstrings.Builderforstringoperations.1)Usebytes.Bufferforworkingwithbyteslices,binarydata,appendingdifferentdatatypes,andwritingtoio.Writer.2)Usestrings.Builderforstrin

How to use the 'strings' package to manipulate strings in Go step by stepHow to use the 'strings' package to manipulate strings in Go step by stepMay 13, 2025 am 12:12 AM

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Go strings package: how to improve my code?Go strings package: how to improve my code?May 13, 2025 am 12:10 AM

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

What are the most useful functions in the GO bytes package?What are the most useful functions in the GO bytes package?May 13, 2025 am 12:09 AM

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Mastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive GuideMastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive GuideMay 13, 2025 am 12:07 AM

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.