| 192 | } |
| 193 | |
| 194 | async function getCryptoKey(key_location) { |
| 195 | const NOT_FOUND = 5; |
| 196 | |
| 197 | // Instantiates a client. |
| 198 | const client = new KeyManagementServiceClient(); |
| 199 | |
| 200 | // Build the parent key ring name. |
| 201 | const keyRingName = client.keyRingPath(PROJECT_ID, key_location, KEY_RING_ID); |
| 202 | |
| 203 | // Get key ring. |
| 204 | try { |
| 205 | await client.getKeyRing({name: keyRingName}); |
| 206 | } catch (err) { |
| 207 | // Create key ring if it doesn't exist. |
| 208 | if (err.code === NOT_FOUND) { |
| 209 | // Build the parent location name. |
| 210 | const locationName = client.locationPath(PROJECT_ID, key_location); |
| 211 | await client.createKeyRing({ |
| 212 | parent: locationName, |
| 213 | keyRingId: KEY_RING_ID, |
| 214 | }); |
| 215 | } else { |
| 216 | throw err; |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | // Get key. |
| 221 | try { |
| 222 | // Build the key name |
| 223 | const keyName = client.cryptoKeyPath( |
| 224 | PROJECT_ID, |
| 225 | key_location, |
| 226 | KEY_RING_ID, |
| 227 | KEY_ID |
| 228 | ); |
| 229 | const [key] = await client.getCryptoKey({ |
| 230 | name: keyName, |
| 231 | }); |
| 232 | return key; |
| 233 | } catch (err) { |
| 234 | // Create key if it doesn't exist. |
| 235 | if (err.code === NOT_FOUND) { |
| 236 | const [key] = await client.createCryptoKey({ |
| 237 | parent: keyRingName, |
| 238 | cryptoKeyId: KEY_ID, |
| 239 | cryptoKey: { |
| 240 | purpose: 'ENCRYPT_DECRYPT', |
| 241 | versionTemplate: { |
| 242 | algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION', |
| 243 | }, |
| 244 | }, |
| 245 | }); |
| 246 | return key; |
| 247 | } else { |
| 248 | throw err; |
| 249 | } |
| 250 | } |
| 251 | } |