GoLang实现google authenticator的CLI工具

简介: 两步认证在很多验证中都要使用。如果在手机客户端上,如果使用电脑,每次都要拿出手机,手动输入。还要担心会过时。效率不是很高。我现在的处理方式以下方式:MAC上alfred workflow支持Chrom扩展支持手机客户端CLI记录工具今天主要介绍CLI工具,我现在在golang,找一些练手的项目.

两步认证在很多验证中都要使用。如果在手机客户端上,如果使用电脑,每次都要拿出手机,手动输入。还要担心会过时。效率不是很高。

我现在的处理方式以下方式:

  • MAC上alfred workflow支持
  • Chrom扩展支持
  • 手机客户端
  • CLI记录工具

今天主要介绍CLI工具,我现在在golang,找一些练手的项目.

先上代码


package main

import (
    "fmt"
    "os"
    "log"
    "sort"
    "github.com/urfave/cli"
    "gopkg.in/ini.v1"
    "crypto/hmac"
    "crypto/sha1"
    "strings"
    "encoding/base32"
    "time"
    "github.com/atotto/clipboard"
    "strconv"
)


func toBytes(value int64) []byte {
    var result []byte
    mask := int64(0xFF)
    shifts := [8]uint16{56, 48, 40, 32, 24, 16, 8, 0}
    for _, shift := range shifts {
        result = append(result, byte((value>>shift)&mask))
    }
    return result
}

func toUint32(bytes []byte) uint32 {
    return (uint32(bytes[0]) << 24) + (uint32(bytes[1]) << 16) +
        (uint32(bytes[2]) << 8) + uint32(bytes[3])
}

func oneTimePassword(key []byte, value []byte) uint32 {
    // sign the value using HMAC-SHA1
    hmacSha1 := hmac.New(sha1.New, key)
    hmacSha1.Write(value)
    hash := hmacSha1.Sum(nil)
    
    offset := hash[len(hash)-1] & 0x0F

    // get a 32-bit (4-byte) chunk from the hash starting at offset
    hashParts := hash[offset : offset+4]

    // ignore the most significant bit as per RFC 4226
    hashParts[0] = hashParts[0] & 0x7F

    number := toUint32(hashParts)

    // size to 6 digits
    // one million is the first number with 7 digits so the remainder
    // of the division will always return < 7 digits
    pwd := number % 1000000

    return pwd
}



func Cli() {

    app := cli.NewApp()
    app.Name = "Google Authentiator CLI"
    app.Usage = "Create, List, Delete, Copy your GA"
    app.Version = "0.0.1"
    app.Commands = []cli.Command {
        {
            Name: "list",
            Aliases: []string{"l"},
            Usage: "list | l",
            Description: "list all item",
            Category: "Show",
            Action: func(c *cli.Context) error {
                list()
                return nil
            },
        },
        {
            Name: "show",
            Aliases: []string{"s"},
            Usage: "show | s github.com",
            Description: "show all item",
            Category: "Show",
            Action: func(c *cli.Context) error {
                item := c.Args().First()
                show(item)
                return nil
            },
        },
        {
            Name: "copy",
            Aliases: []string{"c"},
            Usage: "copy | c github.com",
            UsageText: "copy ga to Clipboard",
            Category: "Show",
            Action: func(c *cli.Context) error {
                item := c.Args().First()
                copy(item)
                return nil
            },
        },
        {
            Name: "create",
            Aliases: []string{"r"},
            Usage: "create| r github.com xxxxxxxxxx",
            UsageText: "create a new ga Secrete item",
            Category: "Store",
            Action: func(c *cli.Context) error {
                item := c.Args().First()
                secret := c.Args()[1]
                create(item, secret)
                return nil
            },
        },
        {
            Name: "modify",
            Aliases: []string{"m"},
            Usage: "modify | m github.com xxxxxxxxx",
            UsageText: "Modify One item Secrete",
            Category: "Store",
            Action: func(c *cli.Context) error {
                item := c.Args().First()
                secret := c.Args()[1]
                modify(item, secret)
                return nil
            },
        },
        {
            Name: "delete",
            Aliases: []string{"d"},
            Usage: "delete | d github.com",
            UsageText: "Delete One item Secrete",
            Category: "Store",
            Action: func(c *cli.Context) error {
                delete(c.Args().First())
                return nil
            },
        },

    }
    app.Action = func(c *cli.Context) error {
        fmt.Println("you can use list")
        return nil
    }

    sort.Sort(cli.FlagsByName(app.Flags))

    cli.HelpFlag = cli.BoolFlag {
        Name: "help, h",
        Usage: "Help!Help!",
    }

    cli.VersionFlag = cli.BoolFlag {
        Name: "print-version, v",
        Usage: "print version",
    }

    err := app.Run(os.Args)
    if err != nil {
        log.Fatal(err)
    }
}


func create(item, secret string) error {
    file,er:=os.Open("/tmp/myga.ini")

    if er != nil {
        file, _ = os.Create("/tmp/myga.ini")
    }
    file.Close()

    cfg, err := ini.Load("/tmp/myga.ini")
    if err != nil {
        panic(err)
    }

    if _, err := cfg.GetSection(item); err == nil {
        fmt.Println(item + " is Exist!!!!")
        os.Exit(1)
    }

    cfg.NewSection(item)
    cfg.Section(item).Key("secret").SetValue(secret)
    cfg.SaveTo("/tmp/myga.ini")
    return nil
}

func show(item string) error {
    file,er:=os.Open("/tmp/myga.ini")

    if er!=nil && os.IsNotExist(er){
        fmt.Println("no data!!!")
        os.Exit(1)
    }
    file.Close()

    cfg, err := ini.Load("/tmp/myga.ini")
    if err != nil {
        panic(err)
    }


    section, err := cfg.GetSection(item)
    if err != nil {
        panic(err)
    }

    key, err := section.GetKey("secret")

    if err != nil {
        panic(err)
    }

    inputNoSpaces := strings.Replace(key.String(), " ", "", -1)
    inputNoSpacesUpper := strings.ToUpper(inputNoSpaces)
    keyS, erro := base32.StdEncoding.DecodeString(inputNoSpacesUpper)
    if erro != nil {
        fmt.Fprintln(os.Stderr, err.Error())
        os.Exit(1)
    }

    // generate a one-time password using the time at 30-second intervals
    epochSeconds := time.Now().Unix()
    pwd := oneTimePassword(keyS, toBytes(epochSeconds/30))

    secondsRemaining := 30 - (epochSeconds % 30)
    fmt.Printf("%06d (%d second(s) remaining)\n", pwd, secondsRemaining)
    return nil

}


func copy(item string) error {
    file,er:=os.Open("/tmp/myga.ini")

    if er!=nil && os.IsNotExist(er){
        fmt.Println("no data!!!")
        os.Exit(1)
    }
    file.Close()

    cfg, err := ini.Load("/tmp/myga.ini")
    if err != nil {
        panic(err)
    }


    section, err := cfg.GetSection(item)
    if err != nil {
        panic(err)
    }

    key, err := section.GetKey("secret")

    if err != nil {
        panic(err)
    }

    inputNoSpaces := strings.Replace(key.String(), " ", "", -1)
    inputNoSpacesUpper := strings.ToUpper(inputNoSpaces)
    keyS, erro := base32.StdEncoding.DecodeString(inputNoSpacesUpper)
    if erro != nil {
        fmt.Fprintln(os.Stderr, err.Error())
        os.Exit(1)
    }

    // generate a one-time password using the time at 30-second intervals
    epochSeconds := time.Now().Unix()
    pwd := oneTimePassword(keyS, toBytes(epochSeconds/30))

    secondsRemaining := 30 - (epochSeconds % 30)
    clipStr := strconv.Itoa(int(pwd))
    clipboard.WriteAll(clipStr)
    fmt.Printf("%06d (%d second(s) remaining)\n", pwd, secondsRemaining)
    return nil

}




func list() error {
    file,er:=os.Open("/tmp/myga.ini")

    if er!=nil && os.IsNotExist(er){
        fmt.Println("no data!!!")
        os.Exit(1)
    }
    file.Close()

    cfg, err := ini.Load("/tmp/myga.ini")
    if err != nil {
        panic(err)
    }


    sections := cfg.Sections()

    for _,v := range sections {
        fmt.Println(v.Name())
    }
    return nil

}




func delete(item string) error {
    file,er:=os.Open("/tmp/myga.ini")

    if er!=nil && os.IsNotExist(er){
        file, _ = os.Create("/tmp/myga.ini")
    }
    file.Close()

    cfg, err := ini.Load("/tmp/myga.ini")
    if err != nil {
        panic(err)
    }

    if _, err := cfg.GetSection(item); err != nil {
        fmt.Println(item + " is not Exist!!!!")
        os.Exit(1)
    }

    cfg.DeleteSection(item)
    cfg.SaveTo("/tmp/myga.ini")
    fmt.Println("ok!!!")
    return nil
}

func modify(item string, secret string) error {
    file,er:=os.Open("/tmp/myga.ini")

    if er!=nil && os.IsNotExist(er){
        file, _ = os.Create("/tmp/myga.ini")
    }
    file.Close()

    cfg, err := ini.Load("/tmp/myga.ini")
    if err != nil {
        panic(err)
    }

    if _, err := cfg.GetSection(item); err != nil {
        fmt.Println(item + " is not Exist!!!!")
        os.Exit(1)
    }

    cfg.Section(item).Key("secret").SetValue(secret)
    cfg.SaveTo("/tmp/myga.ini")
    return nil
}


func main() {
    Cli()
}

上面实现的功能有

  • ga的创建,更新,删除,数据都是保存在本地的
  • 显示所有条目
  • 显示验证码,复制验证码到黏贴板上

后续介绍其他的方式以及ga的工作原理。

目录
相关文章
|
10月前
|
NoSQL 小程序 Cloud Native
你是使用什么工具调试 golang 程序的?
你是使用什么工具调试 golang 程序的?
153 0
|
11月前
|
测试技术 Go 开发工具
100天精通Golang(基础入门篇)——第3天:Go语言的执行原理及常用命令、编码规范和常用工具
100天精通Golang(基础入门篇)——第3天:Go语言的执行原理及常用命令、编码规范和常用工具
213 1
|
14天前
|
NoSQL Java 测试技术
Golang内存分析工具gctrace和pprof实战
文章详细介绍了Golang的两个内存分析工具gctrace和pprof的使用方法,通过实例分析展示了如何通过gctrace跟踪GC的不同阶段耗时与内存量对比,以及如何使用pprof进行内存分析和调优。
45 0
Golang内存分析工具gctrace和pprof实战
|
3月前
|
SQL 关系型数据库 MySQL
mysqldiff - Golang 针对 MySQL 数据库表结构的差异 SQL 工具
Golang 针对 MySQL 数据库表结构的差异 SQL 工具。https://github.com/camry/mysqldiff
78 7
|
3月前
|
人工智能 自然语言处理 机器人
[AI Google] 新的生成媒体模型和工具,专为创作者设计和构建
探索谷歌最新的生成媒体模型:用于高分辨率视频生成的 Veo 和用于卓越文本生成图像能力的 Imagen 3。还可以了解使用 Music AI Sandbox 创作的新演示录音。
[AI Google] 新的生成媒体模型和工具,专为创作者设计和构建
|
4月前
|
缓存 Java Maven
Google guava工具类库的介绍和使用
Google guava工具类库的介绍和使用
|
4月前
|
Java 数据安全/隐私保护
SpringBoot【集成Thumbnailator】Google开源图片工具缩放+区域裁剪+水印+旋转+保持比例等(保姆级教程含源代码)
SpringBoot【集成Thumbnailator】Google开源图片工具缩放+区域裁剪+水印+旋转+保持比例等(保姆级教程含源代码)
214 0
|
11月前
|
机器学习/深度学习 Prometheus Kubernetes
谁在用Go语言?Google、Uber、Netflix等大公司广泛采用
谁在用Go语言?Google、Uber、Netflix等大公司广泛采用
72 0
|
12月前
|
SQL 测试技术 Go
Golang实用进阶工具
Golang实用进阶工具
48 0
|
Java Go 开发工具
Go入门篇:(一)golang的安装和编辑工具安装
Go入门篇:(一)golang的安装和编辑工具安装
402 0