doujia4619
2015-09-01 10:39
浏览 106
已采纳

使用crypto / aes lib加密Golang文件

I am trying to encrypt a file using the Go crypto/aes package. I have so far:

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
}

My first question is, how can I improve the way I am generating the IV? And secondly, there is no output file, so how do I stream the file through XORKeyStream?

图片转代码服务由CSDN问答提供 功能建议

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

  func crypto(源字符串,localdir字符串)错误{
 
 src:= filepath.Join(“ / home / bacula / cloud-backup  /“ + localdir,源)
 dst:=文件路径。Join(src +” .aes“)
 
 fmt.Println(src)
 fmt.Println(dst)
键:= [] 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))
返回nil 
}  
   
 
 

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongting7352 2015-09-01 11:59
    已采纳

    There is an example in the crypto/cipher package documentation.

    I've tweaked the example to make new example for you:

    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
    }
    
    点赞 评论

相关推荐 更多相似问题