GenerateKey generates a new HMAC key.
( extractable bool, keyUsages []CryptoKeyUsage, )
| 85 | |
| 86 | // GenerateKey generates a new HMAC key. |
| 87 | func (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 |
nothing calls this directly
no test coverage detected