du1913 2016-08-31 21:34
浏览 126
已采纳

Golang加密:加密文件不带IV前缀

I am using an IV in cipher.NewOFB, but my encrypted file never gets prefixed with it. I followed the golang examples at https://golang.org/pkg/crypto/cipher/, but can't seem to figure out why the prefix isn't being considered.

Does anyone see what the problem is?

func generateRandomIV(length int) []byte {
    iv := make([]byte, aes.BlockSize)

    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        panic(err)
    }

    return iv
}


func encryptFile(filename, keystring string) error {
    readFile, err := os.Open(filename)
    iv := generateRandomIV(aes.BlockSize)

    outFile, err := os.OpenFile(filename+".enc", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
    if err != nil {
        panic(err)
    }

    defer readFile.Close()
    defer outFile.Close()

    key := []byte(keystring)

    block, err := aes.NewCipher(key)

    if err != nil {
        panic(err)
    }

    fmt.Println("IV:", iv)
    writer := &cipher.StreamWriter{S: cipher.NewOFB(block, iv), W: outFile}

    if _, err := io.Copy(writer, readFile); err != nil {
        return err
    }

    return nil
}
  • 写回答

1条回答 默认 最新

  • doudun2565 2016-08-31 21:57
    关注

    Add the IV prefix yourself or pre-share the IV. If you prefix it you will have the remove it and apply it on decryption.

    How an IV is shared is not part of the encryption standard, it is a developer choice. Prefixing the IV is common but not required or the only way, it is however a good choice.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看