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.

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

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?