我正在尝试在golang中实现以下JS代码,但在golang的加密软件包中找不到任何导出 key 方法:
JS代码:
return Crypto.subtle.generateKey({
name: 'AES-GCM',
length: 256
}, !0, ['encrypt', 'decrypt']).then(function(t) {
const n = A.subtle.exportKey('raw', t);
return n
}).then(function(n) {
console.log(n)
}).catch(function(t) {
throw t
})
最佳答案
crypto.subtle.exportKey('raw', key)
的等效项只是使用[]byte
值。
这已经是对称 key 的格式。例如:aes使用:func NewCipher(key []byte) (cipher.Block, error)
。
因此,为AES256生成 key 并打印其原始值将遵循以下方式(playground link):
import (
"crypto/rand" // Careful: do not use "math/rand".
"fmt"
)
func main() {
key := make([]byte, 32) // 32 bytes for AES256.
_, err := rand.Read(key) // read from random source
if err != nil {
// handle error
}
fmt.Println(key)
}
对于其他导出格式和 key ,您可能需要研究x509,pem和每个算法的 key 生成功能。
关于go - Golang中crypto.subtle.exportKey的替代方法是什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60128002/