doujia4619 2015-09-01 10:39 采纳率: 0%
浏览 135
已采纳

使用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?

  • 写回答

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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 qgcomp混合物线性模型分析的代码出现错误:Model aliasing occurred
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'