您好,这是我第一次真正尝试编写实际的 Go 命令行程序,所以请原谅我也从互联网上删除了一些代码。我实际上想要做的是能够选择何时加密或解密,同时仍然能够选择 src 文件和 dest 文件。在此先感谢您的帮助。我找不到任何可靠的解释,或者至少我找不到任何东西。package mainimport ("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) }
1 回答
饮歌长啸
TA贡献1951条经验 获得超3个赞
使用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)
}
}
- 1 回答
- 0 关注
- 135 浏览
添加回答
举报
0/150
提交
取消