Golang generating a 32 byte key

huangapple go评论78阅读模式
英文:

Golang generating a 32 byte key

问题

我正在使用这个库来处理会话。

https://github.com/codegangsta/martini-contrib/tree/master/sessions

它说:

建议使用32或64字节的身份验证密钥。如果设置了加密密钥,它必须是16、24或32字节,以选择AES-128、AES-192或AES-256模式。

如何生成一个64字节的密钥,是否就像[]byte"64characterslongstring"这样简单,我认为并不总是那么简单。

英文:

I am using this library for sessions.

https://github.com/codegangsta/martini-contrib/tree/master/sessions

It says that:

It is recommended to use an authentication key with 32 or 64 bytes. The encryption key, if set, must be either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256 modes.

How do I generate a 64 byte key, is it as straightforward as []byte"64characterslongstring", I thought it is not always so straight forward?

答案1

得分: 36

生成一个包含64个随机字节的切片:

package main

import "crypto/rand"

func main() {
    key := make([]byte, 64)

    _, err := rand.Read(key)
    if err != nil {
        // 在这里处理错误
    }
}

演示代码可以在这里找到。

英文:

To generate a slice of 64 random bytes:

package main

import "crypto/rand"

func main() {
	key := make([]byte, 64)

	_, err := rand.Read(key)
	if err != nil {
		// handle error here
	}
}

Demo here.

huangapple
  • 本文由 发表于 2014年1月16日 19:17:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/21160258.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定