使用crypto / aes lib进行Golang文件加密

时间:2015-09-01 10:39:11

标签: encryption go aes

我正在尝试使用Go crypto / aes包加密文件。我到目前为止:

func encrypt(source string, localdir string) error {

    src := filepath.Join("/home/bacula/cloud-backup/"+localdir, source)
    dst := filepath.Join(src + ".aes")

    fmt.Println(src)
    fmt.Println(dst)
    key := []byte("example key 1234")

    iv := []byte(key)[:aes.BlockSize]

    aesBlockEncrypter, err := aes.NewCipher([]byte(key))
    if err != nil {
            return err
    }
    aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, iv)
    aesEncrypter.XORKeyStream([]byte(dst), []byte(src))
    return nil
}

我的第一个问题是,我如何改进生成IV的方式?其次,没有输出文件,那么如何通过XORKeyStream传输文件?

1 个答案:

答案 0 :(得分:9)

crypto/cipherdocumentation中有一个例子。

我已经调整了这个例子,为你做了一个新的例子:

func main() {
    // read content from your file
    plaintext, err := ioutil.ReadFile("you_file_to_be_encrypted")
    if err != nil {
        panic(err.Error())
    }

    // this is a key
    key := []byte("example key 1234")

    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err)
    }

    // The IV needs to be unique, but not secure. Therefore it's common to
    // include it at the beginning of the ciphertext.
    ciphertext := make([]byte, aes.BlockSize+len(plaintext))
    iv := ciphertext[:aes.BlockSize]
    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        panic(err)
    }

    stream := cipher.NewCFBEncrypter(block, iv)
    stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)

    // create a new file for saving the encrypted data.
    f, err := os.Create("a_aes.txt")
    if err != nil {
        panic(err.Error())
    }
    _, err = io.Copy(f, bytes.NewReader(ciphertext))
    if err != nil {
        panic(err.Error())
    }

    // done
}