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