MCPcopy
hub / github.com/grafana/k6 / GenerateKey

Method GenerateKey

internal/js/modules/k6/webcrypto/hmac.go:87–161  ·  view source on GitHub ↗

GenerateKey generates a new HMAC key.

(
	extractable bool,
	keyUsages []CryptoKeyUsage,
)

Source from the content-addressed store, hash-verified

85
86// GenerateKey generates a new HMAC key.
87func (hkgp *HMACKeyGenParams) GenerateKey(
88 extractable bool,
89 keyUsages []CryptoKeyUsage,
90) (CryptoKeyGenerationResult, error) {
91 // 1.
92 for _, usage := range keyUsages {
93 switch usage {
94 case SignCryptoKeyUsage, VerifyCryptoKeyUsage:
95 continue
96 default:
97 return nil, NewError(SyntaxError, "invalid key usage: "+usage)
98 }
99 }
100
101 // 2.
102 // We extract the length attribute from the algorithm object, as it's not
103 // part of the normalized algorithm, and as accessing the runtime from the
104 // callback below could lead to a race condition.
105 if !hkgp.Length.Valid {
106 var length bitLength
107 switch hkgp.Hash.Name {
108 case SHA1:
109 length = byteLength(sha1.BlockSize).asBitLength()
110 case SHA256:
111 length = byteLength(sha256.BlockSize).asBitLength()
112 case SHA384:
113 length = byteLength(sha512.BlockSize).asBitLength()
114 case SHA512:
115 length = byteLength(sha512.BlockSize).asBitLength()
116 default:
117 // This case should never happen, as the normalization algorithm
118 // should have thrown an error if the hash algorithm is invalid.
119 return nil, NewError(ImplementationError, "invalid hash algorithm: "+hkgp.Hash.Name)
120 }
121
122 hkgp.Length = null.IntFrom(int64(length))
123 }
124
125 if hkgp.Length.Int64 == 0 {
126 return nil, NewError(OperationError, "algorithm's length cannot be 0")
127 }
128
129 // 3.
130 randomKey := make([]byte, bitLength(hkgp.Length.Int64).asByteLength())
131 if _, err := rand.Read(randomKey); err != nil {
132 // 4.
133 return nil, NewError(OperationError, "failed to generate random key; reason: "+err.Error())
134 }
135
136 // 5.
137 key := &CryptoKey{Type: SecretCryptoKeyType, handle: randomKey}
138
139 // 6.
140 algorithm := &HMACKeyAlgorithm{}
141
142 // 7.
143 algorithm.Name = HMAC
144 algorithm.Length = hkgp.Length.Int64

Callers

nothing calls this directly

Calls 7

NewErrorFunction · 0.85
byteLengthTypeAlias · 0.85
bitLengthTypeAlias · 0.85
asBitLengthMethod · 0.80
asByteLengthMethod · 0.80
ReadMethod · 0.65
ErrorMethod · 0.65

Tested by

no test coverage detected