Skip to content

Instantly share code, notes, and snippets.

@lynsei
Created November 16, 2021 16:57
Show Gist options
  • Save lynsei/7e81b621c871d157a446ae2048f4b27c to your computer and use it in GitHub Desktop.
Save lynsei/7e81b621c871d157a446ae2048f4b27c to your computer and use it in GitHub Desktop.
next.js > cryptographic implementation for comparison to some other operatiuons I'm doing with crypto
import type { NextRequest } from 'next/server'
export async function middleware(req: NextRequest) {
// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/subtle
const plainText = 'Hello from the Edge!'
const password = 'hunter2'
const ptUtf8 = new TextEncoder().encode(plainText)
const pwUtf8 = new TextEncoder().encode(password)
const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8)
// Encrpyt
const iv = crypto.getRandomValues(new Uint8Array(12))
const alg = { name: 'AES-GCM', iv: iv }
const encrpytKey = await crypto.subtle.importKey('raw', pwHash, alg, false, [
'encrypt',
])
const encrypted = await crypto.subtle.encrypt(alg, encrpytKey, ptUtf8)
// Decrypt
const decryptKey = await crypto.subtle.importKey('raw', pwHash, alg, false, [
'decrypt',
])
const ptBuffer = await crypto.subtle.decrypt(alg, decryptKey, encrypted)
const decryptedText = new TextDecoder().decode(ptBuffer)
return new Response(
JSON.stringify({
// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID
uuid: crypto.randomUUID(),
// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
randomValues: crypto.getRandomValues(new Uint32Array(10)),
plainText,
password,
decryptedText,
iv,
}),
{ headers: { 'Content-Type': 'application/json' } }
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment