猿问

我如何使用标志来选择我想调用的函数

您好,这是我第一次真正尝试编写实际的 Go 命令行程序,所以请原谅我也从互联网上删除了一些代码。我实际上想要做的是能够选择何时加密或解密,同时仍然能够选择 src 文件和 dest 文件。在此先感谢您的帮助。我找不到任何可靠的解释,或者至少我找不到任何东西。


package main


import (

"crypto/aes"

"crypto/cipher"

"crypto/rand"

"errors"

"io"

"io/ioutil"

"log"

"os"

)


func decrypt(key, ciphertext []byte) (plaintext []byte, err error) {


  var block cipher.Block


  if block, err = aes.NewCipher(key); err != nil {

      return

 }


  if len(ciphertext) < aes.BlockSize {

    err = errors.New("ciphertext too short")

    return

 }


  iv := ciphertext[:aes.BlockSize]

  ciphertext = ciphertext[aes.BlockSize:]


  cfb := cipher.NewCFBDecrypter(block, iv)

  cfb.XORKeyStream(ciphertext, ciphertext)


  plaintext = ciphertext


   return

 }


func encrypt(key, text []byte) (ciphertext []byte, err error) {


  var block cipher.Block


  if block, err = aes.NewCipher(key); err != nil {

      return nil, err

 }


  ciphertext = make([]byte, aes.BlockSize+len(string(text)))



  iv := ciphertext[:aes.BlockSize]

  if _, err = io.ReadFull(rand.Reader, iv); err != nil {

      return

 }


  cfb := cipher.NewCFBEncrypter(block, iv)

  cfb.XORKeyStream(ciphertext[aes.BlockSize:], text)


  return

 }


func encryptFileData(srcFile, destFile string) {

  if len(os.Args) > 1 {

      srcFile = os.Args[1]

  }

  if len(os.Args) > 2 {

      destFile = os.Args[2]

 }

  var cipherText, plainText []byte

  var err error




  key := []byte("abcdefg123456789")


  plainText, _ = ioutil.ReadFile(srcFile)

  if cipherText, err = encrypt(key, plainText); err != nil {

      log.Fatal(err)

  }

  ioutil.WriteFile(destFile, cipherText, 0755)


   return

  }


func decryptFileData(srcFile, destFile string) {

  if len(os.Args) > 1 {

      srcFile = os.Args[1]

  }

  if len(os.Args) > 2 {

      destFile = os.Args[2]

  }

  var cipherText, plainText []byte

  var err error


  key := []byte("abcdefg123456789")


  cipherText, _ = ioutil.ReadFile(srcFile)

  if plainText, err = decrypt(key, cipherText); err != nil {

      log.Fatal(err)

  }



Qyouu
浏览 136回答 1
1回答

饮歌长啸

使用flag包。例如:func main() {&nbsp; &nbsp; encrypt := flag.Bool("encrypt", false, "encrypt file")&nbsp; &nbsp; decrypt := flag.Bool("decrypt", false, "decrypt file")&nbsp; &nbsp; flag.Parse()&nbsp; &nbsp; srcFile, destFile := flag.Arg(0), flag.Arg(1)&nbsp; &nbsp; if *encrypt {&nbsp; &nbsp; &nbsp; &nbsp; encryptFileData(srcFile, destFile)&nbsp; &nbsp; }&nbsp; &nbsp; if *decrypt {&nbsp; &nbsp; &nbsp; &nbsp; decryptFileData(srcFile, destFile)&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Go
我要回答