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 如何用数码管显示学号(相关搜索:单片机)
  • ¥15 错误于library(org.Hs.eg.db): 不存在叫‘org.Hs.eg.db’这个名称的程序包,如何解决?
  • ¥60 求一个图片处理程序,要求将图像大小跟现实生活中的大小按比例联系起来的
  • ¥50 求一位精通京东相关开发的专家
  • ¥100 求懂行的大ge给小di解答下!
  • ¥15 pcl运行在qt msvc2019环境运行效率低于visual studio 2019
  • ¥15 MAUI,Zxing扫码,华为手机没反应。可提高悬赏
  • ¥15 python运行报错 ModuleNotFoundError: No module named 'torch'
  • ¥100 华为手机私有App后台保活
  • ¥15 sqlserver中加密的密码字段查询问题