Debian Codegraph @

example/readline-pass-strength/readline-pass-strength.go

raw symbols SCIP
1 // This is a small example using readline to read a password
2 // and check it's strength while typing using the zxcvbn library.
3 // Depending on the strength the prompt is colored nicely to indicate strength.
4 //
5 // This file is licensed under the WTFPL:
6 //
7 // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
8 // Version 2, December 2004
9 //
10 // Copyright (C) 2004 Sam Hocevar <[email protected]>
11 //
12 // Everyone is permitted to copy and distribute verbatim or modified
13 // copies of this license document, and changing it is allowed as long
14 // as the name is changed.
15 //
16 // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
17 // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
18 //
19 // 0. You just DO WHAT THE FUCK YOU WANT TO.
20 package main
21
22 import (
23 "fmt"
24
25 "github.com/chzyer/readline"
26 zxcvbn "github.com/nbutton23/zxcvbn-go"
27 )
28
29 const (
30 Cyan = 36
31 Green = 32
32 Magenta = 35
33 Red = 31
34 Yellow = 33
35 BackgroundRed = 41
36 )
37
38 // Reset sequence
39 var ColorResetEscape = "\033[0m"
40
41 // ColorResetEscape translates a ANSI color number to a color escape.
42 func ColorEscape(color int) string {
43 return fmt.Sprintf("\033[0;%dm", color)
44 }
45
46 // Colorize the msg using ANSI color escapes
47 func Colorize(msg string, color int) string {
48 return ColorEscape(color) + msg + ColorResetEscape
49 }
50
51 func createStrengthPrompt(password []rune) string {
52 symbol, color := "", Red
53 strength := zxcvbn.PasswordStrength(string(password), nil)
54
55 switch {
56 case strength.Score <= 1:
57 symbol = "✗"
58 color = Red
59 case strength.Score <= 2:
60 symbol = "⚡"
61 color = Magenta
62 case strength.Score <= 3:
63 symbol = "⚠"
64 color = Yellow
65 case strength.Score <= 4:
66 symbol = "✔"
67 color = Green
68 }
69
70 prompt := Colorize(symbol, color)
71 if strength.Entropy > 0 {
72 entropy := fmt.Sprintf(" %3.0f", strength.Entropy)
73 prompt += Colorize(entropy, Cyan)
74 } else {
75 prompt += Colorize(" ENT", Cyan)
76 }
77
78 prompt += Colorize(" New Password: ", color)
79 return prompt
80 }
81
82 func main() {
83 rl, err := readline.New("")
84 if err != nil {
85 return
86 }
87 defer rl.Close()
88
89 setPasswordCfg := rl.GenPasswordConfig()
90 setPasswordCfg.SetListener(func(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool) {
91 rl.SetPrompt(createStrengthPrompt(line))
92 rl.Refresh()
93 return nil, 0, false
94 })
95
96 pswd, err := rl.ReadPasswordWithConfig(setPasswordCfg)
97 if err != nil {
98 return
99 }
100
101 fmt.Println("Your password was:", string(pswd))
102 }