首页 > 解决方案 > golang中crypto.subtle.exportKey的替代品是什么

问题描述

我正在尝试在golang中实现下面的JS代码,但是我在golang的crypto包中找不到任何导出密钥方法:

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
        })

标签: gocryptographyaesaes-gcm

解决方案


的等价物crypto.subtle.exportKey('raw', key)只是简单地使用该[]byte值。

这已经是对称密钥的格式。例如:aes使用:func NewCipher(key []byte) (cipher.Block, error).

因此,为 AES256 生成密钥并打印其原始值将类似于以下内容(游乐场链接):

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)
}

对于其他导出格式和密钥,您可能需要查看x509pem和按算法生成密钥的功能。


推荐阅读