您好,这是我第一次真正尝试编写实际的 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)
}
饮歌长啸
相关分类