草庐IT

random - crypto/rand read() 的两个返回值在什么情况下有用?

coder 2024-07-11 原文

crypto/rand 的典型用法是这样的:

salt := make([]byte, saltLength)
n,err := rand.Read(salt)

它用一系列随机字节填充我在这里标记为“salt”的字节 slice 。

在什么情况下随机数生成器可能会失败?在 err 不为零的情况下退回到数学/兰德等价物是否不安全?

由于字节 slice 的长度是已知的,n 对我来说似乎也没用,我有什么理由不直接使用 _,err 代替它吗?

最佳答案

为了安全起见,您的代码应该看起来更像这样:

package main

import (
    "crypto/rand"
    "fmt"
)

func main() {
    saltLength := 16
    salt := make([]byte, saltLength)
    n, err := rand.Read(salt[:cap(salt)])
    if err != nil {
        // handle error
    }
    salt = salt[:n]
    if len(salt) != saltLength {
        // handle error
    }
    fmt.Println(len(salt), salt)
}

输出:

16 [191 235 81 37 175 238 93 202 230 158 41 199 202 85 67 209]
如果可用的熵不足,

n 可能小于 len(salt)。您应该始终检查错误。

例如,获取随机数序列的众多方法之一是 Linux 上的 getrandom 系统调用或 Windows 上的 CryptGenRandom API 调用。

引用资料:

random: introduce getrandom(2) system call

CryptGenRandom function

附录:

crypto/rand 包是一个加密安全的伪随机数生成器。包 math/rand 不是加密安全的。

即使是一个简单的程序,路径也太多了,无法全部测试。因此,编写零缺陷和零错误程序的唯一方法是编写可读、可维护且可证明正确的代码。 Niklaus Wirth 的系统编程是一本很好的入门书。花时间构建一个健壮的通用形式是值得的,它可以很容易地适应每个特殊情况,并且随着需求的变化也很容易维护。

例如,对于 io.Reader 接口(interface),典型的用法是循环模式。

func Reader(rdr io.Reader) error {
    bufLen := 256
    buf := make([]byte, bufLen)
    for {
        n, err := rdr.Read(buf[:cap(buf)])
        if n == 0 {
            if err == nil {
                continue
            }
            if err == io.EOF {
                break
            }
            return err
        }
        buf = buf[:n]
        // process read buffer
        if err != nil && err != io.EOF {
            return err
        }
    }
    return nil
}

type Reader

type Reader interface {
        Read(p []byte) (n int, err error)
}

Reader is the interface that wraps the basic Read method.

Read reads up to len(p) bytes into p. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. Even if Read returns n < len(p), it may use all of p as scratch space during the call. If some data is available but not len(p) bytes, Read conventionally returns what is available instead of waiting for more.

When Read encounters an error or end-of-file condition after successfully reading n > 0 bytes, it returns the number of bytes read. It may return the (non-nil) error from the same call or return the error (and n == 0) from a subsequent call. An instance of this general case is that a Reader returning a non-zero number of bytes at the end of the input stream may return either err == EOF or err == nil. The next Read should return 0, EOF regardless.

Callers should always process the n > 0 bytes returned before considering the error err. Doing so correctly handles I/O errors that happen after reading some bytes and also both of the allowed EOF behaviors.

Implementations of Read are discouraged from returning a zero byte count with a nil error, and callers should treat that situation as a no-op.

我们只想在开始Read 循环之前分配一次缓冲区。但是,我们希望编译器和运行时检测我们是否在 Read 循环中超出有效缓冲区长度 n,因此我们编写 buf = buf[:n ]。然而,当我们循环到下一个 Read 时,我们明确想要完整的缓冲区:buf[:cap(buf)

Read(buf[:cap(buf)])永远不会错。即使您现在可能没有 Read 循环,您以后可能会添加一个,并且您可能会忘记重置缓冲区长度。特定的 Read 实现可能有特殊情况,例如底层 ReadFull。现在你必须阅读和监控底层代码来证明你的代码是正确的。文档并不总是可靠的。而且您无法安全地切换到另一个 io.Reader Read 实现。

当您访问 salt slice 时,salt[:len(salt)],您使用的是 len(salt) 而不是 n。如果它们不同,则说明存在错误。

"implementations should follow a general principle of robustness: be conservative in what you do, be liberal in what you accept from others." Jon Postel

关于random - crypto/rand read() 的两个返回值在什么情况下有用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26577917/

有关random - crypto/rand read() 的两个返回值在什么情况下有用?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  3. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  4. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  5. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  6. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  7. ruby - 默认情况下使选项为 false - 2

    这是在Ruby中设置默认值的常用方法:classQuietByDefaultdefinitialize(opts={})@verbose=opts[:verbose]endend这是一个容易落入的陷阱:classVerboseNoMatterWhatdefinitialize(opts={})@verbose=opts[:verbose]||trueendend正确的做法是:classVerboseByDefaultdefinitialize(opts={})@verbose=opts.include?(:verbose)?opts[:verbose]:trueendend编写Verb

  8. ruby - ruby 中的 TOPLEVEL_BINDING 是什么? - 2

    它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput

  9. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  10. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

随机推荐