Encrypted responses
Every key issued now answers encrypted. How to read what comes back, and by when.
6 min read
Every API key issued now answers encrypted. Nothing about the request changes — same URL, same x-api-key header, same parameters — but the body comes back as a sealed envelope that only the holder of the matching private key can open. A stolen key is then no longer enough to read anything.
Your current key keeps working — until a date
Sunset and Deprecation headers with the date it stops being accepted. Moving over is creating a new key in the panel and switching to it: the old one goes on working while you deploy, so there is no outage in between. There is no in-place upgrade — a credential either answers in the clear or it does not.What a response looks like
1{2 "crypto": {3 "version": 1,4 "keyId": "ck_9f2c41a08b7e5d3c62f1a4b8",5 "alg": "RSA-OAEP-256",6 "enc": "A256GCM"7 },8 "protected": "eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIiwia2lkIjoi...",9 "wrappedKey": "Q2QwTXAveRyq-sJFH4QmHh60Ru99KWjknnNDywPFldlZ1SCH81JLY_J5qrky...",10 "iv": "x7HbQ2VtYmVkZGVk",11 "payload": "3kPq1mJ0aXNfaXNfdGhlX2NpcGhlcnRleHQ...",12 "tag": "bW5vdF9hX3JlYWxfdGFn"13}
It is a standard JWE
protected, wrappedKey, iv, payload and tag with dots, in that order, and you have a compact JWE (RFC 7516). Hand it to the JOSE library of your language and you are done — there is nothing bespoke to implement.Opening it
1import { compactDecrypt, importPKCS8 } from 'jose'23const privateKey = await importPKCS8(pem, 'RSA-OAEP-256')45const jwe = [e.protected, e.wrappedKey, e.iv, e.payload, e.tag].join('.')6const { plaintext } = await compactDecrypt(jwe, privateKey)78const data = JSON.parse(new TextDecoder().decode(plaintext))
jose. e is the response body; pem is the private key you downloaded.1from jwcrypto import jwe, jwk2import json34key = jwk.JWK.from_pem(open('private.pem', 'rb').read())56token = '.'.join([e['protected'], e['wrappedKey'], e['iv'], e['payload'], e['tag']])7box = jwe.JWE()8box.deserialize(token, key=key)910data = json.loads(box.payload)
jwcrypto.1use phpseclib3\Crypt\RSA;23$b64 = fn($s) => base64_decode(strtr($s, '-_', '+/'));45// 1. unwrap the content key with your private key (OAEP, SHA-256 on both hashes)6$rsa = RSA::loadPrivateKey(file_get_contents('private.pem'))7 ->withPadding(RSA::ENCRYPTION_OAEP)8 ->withHash('sha256')9 ->withMGFHash('sha256');10$cek = $rsa->decrypt($b64($e['wrappedKey']));1112// 2. open the payload; the AAD is the protected header, exactly as it arrived13$json = openssl_decrypt(14 $b64($e['payload']), 'aes-256-gcm', $cek, OPENSSL_RAW_DATA,15 $b64($e['iv']), $b64($e['tag']), $e['protected']16);1718$data = json_decode($json, true);
phpseclib. If you already use a JOSE library such as web-token, use that instead and skip both steps.PHP's built-in openssl will not do this
openssl_private_decrypt with OPENSSL_PKCS1_OAEP_PADDING uses SHA-1 and gives you no way to change it, so it cannot unwrap an RSA-OAEP-256 key and fails with a padding error. Use phpseclib or a JOSE library, as above.Google Apps Script has neither RSA-OAEP nor AES-GCM, and no npm, so the library goes into the project by hand. Add a script file named forge, write var window = globalThis on its first line and paste below it the content of https://cdn.jsdelivr.net/npm/node-forge@1.4.3/dist/forge.min.js — the bundle registers itself on window, which Apps Script does not have. Its SHA-256 is a8b6d50267d709db0411a598efc4c57bffd6127f21410339f71c919e3bde725b. Save the private key in Project Settings → Script properties as HOTELGEST_PRIVATE_KEY, never in the spreadsheet. Anyone who can edit the project can read those properties — for a script bound to the spreadsheet, anyone who can edit the spreadsheet: if that is more people than should read your bookings, decrypt on a server of your own instead and have the sheet call it.
1// base64url without padding -> the binary string forge works with2function fromBase64Url(s) {3 s = s.replace(/-/g, '+').replace(/_/g, '/')4 return forge.util.decode64(s + '===='.slice(s.length % 4 || 4))5}67function openEnvelope(e) {8 if (!e.crypto) throw new Error('not an encrypted response')9 var pem = PropertiesService.getScriptProperties().getProperty('HOTELGEST_PRIVATE_KEY')10 var key = forge.pki.privateKeyFromPem(pem)1112 // 1. unwrap the content key with your private key (OAEP, SHA-256 on both hashes)13 var cek = key.decrypt(fromBase64Url(e.wrappedKey), 'RSA-OAEP', {14 md: forge.md.sha256.create(),15 mgf1: { md: forge.md.sha256.create() },16 })1718 // 2. open the payload; the AAD is the protected header, exactly as it arrived19 var decipher = forge.cipher.createDecipher('AES-GCM', cek)20 decipher.start({21 iv: fromBase64Url(e.iv),22 additionalData: e.protected,23 tag: forge.util.createBuffer(fromBase64Url(e.tag)),24 })25 decipher.update(forge.util.createBuffer(fromBase64Url(e.payload)))26 if (!decipher.finish()) throw new Error('the envelope does not verify')2728 return JSON.parse(forge.util.decodeUtf8(decipher.output.getBytes()))29}3031function fetchDecrypted(url, apiKey) {32 var res = UrlFetchApp.fetch(url, { headers: { 'x-api-key': apiKey } })33 return openEnvelope(JSON.parse(res.getContentText()))34}
node-forge. Pure JavaScript, so it runs where there is no WebCrypto; on large responses expect it to take seconds, not milliseconds. To check the seal as below, with e the parsed response the header is JSON.parse(forge.util.decodeUtf8(fromBase64Url(e.protected))).Check what it was sealed for
Decrypting proves the body was not tampered with. It does NOT prove it is the answer to the request you just made: the same envelope, captured and sent to you again later, decrypts exactly the same. What rules that out is the protected header, and it only works if you look at it.
1// The protected header is the AAD of the seal: if any of this were altered, decryption would2// already have failed. So these values are trustworthy — what is left is to check they are yours.3const header = JSON.parse(Buffer.from(envelope.protected, 'base64url').toString())45if (header.hg.req !== 'GET /api/v2/rooms/:pcode/availability') throw new Error('another endpoint')6if (header.hg.pcode !== expectedPcode) throw new Error('another property')7if (Date.now() / 1000 - header.hg.iat > 120) throw new Error('too old to be this answer')
hg.req is the endpoint that answered, hg.pcode the property the body is about, and hg.iat when it was sealed, in seconds. Two minutes is a starting point: make it as tight as your clock skew allows.What is not encrypted
- •**Errors.** A 401, a 404 or a 500 comes back as the same plain JSON it always did. The messages are generic and carry no data of yours.
- •**Binary bodies**, such as a guest document image. They are bytes with their own content type, ETag and caching, and wrapping them in a JSON envelope would break all three.
- •**Empty responses.** A
204or a304has no body to seal.
The private key
Downloaded once, and only once
**Pick your private key by the keyId in the envelope, not by configuration.** A new pair starts sealing the moment it is issued — there is no grace window — so code that holds a single hardcoded key stops being able to read anything until you deploy the new one. Code that keeps both and selects on keyId sees no interruption at all, which is the whole reason the field is there.
When the old key ends
A key that has been given a retirement date says so in the headers of every response it answers, long before it stops working. Watch for these in your own logs:
1Deprecation: true2Sunset: Thu, 15 Apr 2027 00:00:00 GMT3Link: <https://public-api.hotelgest.com/public/guides/encryption>; rel="sunset"
Sunset, the key answers 401 with a message that says it has been retired.