0

I'm trying to achieve the JS code below in golang, but I can't find any export key methods in crypto package of golang:

JS Code:

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
        })
Ali Padida
  • 1,763
  • 1
  • 16
  • 34

1 Answers1

3

The equivalent of crypto.subtle.exportKey('raw', key) is simply to use the []byte value.

This is already the format for symmetric keys. eg: aes uses: func NewCipher(key []byte) (cipher.Block, error).

So generating a key for AES256 and printing its raw value would be something along the lines of the following (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)
}

For other export formats and keys, you may want to look into x509, pem and per-algorithm key generation functions.

Marc
  • 19,394
  • 6
  • 47
  • 51
  • passing key as nonce argument to aesgcm.Seal gives "crypto/cipher: incorrect nonce length given to GCM", I'm not sure why – Ali Padida Feb 08 '20 at 21:30
  • 1
    The `nonce` is **not** the `key`. To use AES in GCM mode, you need call `cipher.NewGCM` and pass it a AES cipher created using `aes.NewCipher(key)`. See the [example for AES GCM encrypt](https://golang.org/pkg/crypto/cipher/#example_NewGCM_encrypt) – Marc Feb 09 '20 at 14:13