我怎么能使用标志来选择我想要调用哪个功能

时间:2016-03-03 02:58:36

标签: go flags

您好,这是我第一次尝试编写一个实际的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)
  }
  ioutil.WriteFile(destFile, plainText, 0755)

  return
  }

func main() {
  encryptFileData(os.Args[1], os.Args[2])
  decryptFileData(os.Args[1], os.Args[2])
}

1 个答案:

答案 0 :(得分:4)

使用flag包。例如:

func main() {
    encrypt := flag.Bool("encrypt", false, "encrypt file")
    decrypt := flag.Bool("decrypt", false, "decrypt file")
    flag.Parse()

    srcFile, destFile := flag.Arg(0), flag.Arg(1)
    if *encrypt {
        encryptFileData(srcFile, destFile)
    }

    if *decrypt {
        decryptFileData(srcFile, destFile)
    }
}