Skip to content
Tutorials Center
My learning

Topics

Lesson 122 of 132 ยท Projects

Project: Password Generator and QR Code Maker

Build a secure password generator with crypto.getRandomValues and a QR code maker that draws SVG from your own encoder. Two utilities, live in React.

Utility apps are where React shines: a few inputs, a calculation, and an output that updates as you type. In this project you will build two of them. The first is a password generator that uses the browser's cryptographic random source. The second is a QR code maker that turns text into an SVG image using a small encoder written in this lesson, with no library and no network.

Along the way you will practise controlled inputs, derived state, useMemo and how to render graphics with JSX. The previous project used Math.random() for games; this one explains why secrets need something stronger.

Part 1: a password generator

Why not Math.random()? Its output is designed to be fast and "random looking", not unpredictable: someone who sees enough outputs may be able to predict the next ones. crypto.getRandomValues() fills a typed array with values from the operating system's secure generator, and it is the right tool for passwords and tokens.

There is a second trap. If you write value % length on a random 32-bit number, some characters become slightly more likely than others, unless length divides 2ยณยฒ exactly. The fix is rejection sampling: throw away values from the incomplete last "bucket" and draw again.

The generator below guarantees at least one character from each enabled group, fills the rest from the combined pool, then shuffles with a Fisher-Yates shuffle that also uses the secure source. It reports an estimate of the entropy, length ร— logโ‚‚(pool size) bits, which is a reasonable measure for truly random passwords. Copying may be blocked inside the sandbox, so it is wrapped in try/catch with a message.

Part 1: password generator

Look at how little state there is: the options, the current password and a message. The entropy, pool size and label are all derived during rendering. Notice also that regenerating happens in an event handler (update), not in an effect: the password is a result of a user action, so it needs no synchronisation with anything (you might not need an effect).

A password generator that runs in a web page is fine for learning. In real products, prefer your browser's or a password manager's generator, and never send generated secrets to a server just to "display" them.

Part 2: a QR code maker

A QR code is a grid of dark and light squares called modules. Making one is a pipeline, and each step is small enough to understand:

  1. Encode the text as bytes (UTF-8) with a mode marker and a length field, then pad.
  2. Add error correction. Reed-Solomon codes append extra bytes so the code still scans when part of it is dirty or hidden. They are calculated with arithmetic over a Galois field of 256 elements, which sounds scary and is about fifteen lines of code.
  3. Draw the fixed patterns: three big finder squares in the corners, timing lines, and (for versions 2 and up) an alignment square.
  4. Place the bits in a zigzag, two columns at a time, skipping the fixed patterns.
  5. Mask the data with one of eight patterns that break up large blocks, pick the one with the lowest penalty score, and write the chosen mask and error level into the format bits.

Our encoder is deliberately small: byte mode, error correction level M, versions 1 to 5 (up to 84 bytes of text, enough for a short URL or message). It does not do numeric or alphanumeric modes and it scores three of the four official penalty rules, which only affects which valid mask is chosen. We checked its output by decoding it with an independent QR reader for texts of several lengths (including accented characters), and every one read back exactly.

The encoder is plain JavaScript with no React in it, which makes it a pure function you can test, and the component stays tiny. The SVG uses one <path> with a square for every dark module, plus the required four-module quiet zone around the code.

Part 2: a QR code maker

Type something longer than 84 bytes and the error message appears instead of the image: the encoder throws, useMemo catches it and the component turns it into UI. Point a phone camera at the preview to check it. The matrix is recalculated only when text changes, because useMemo caches it (useMemo and useCallback).

Two design choices are worth copying in your own work. The expensive, error-prone part (the encoder) is a plain function outside the component, so it could be unit tested (testing hooks and logic). And the component never stores the image anywhere: the SVG is a derived value of text.

Ideas to extend it

  • Add a colour picker for the dark modules, and warn when contrast with the background is too low to scan (the colour palette project computes contrast).
  • Add a "download SVG" link by building a Blob and URL.createObjectURL (works in a normal page, not in this sandbox).
  • Support larger versions by adding rows to the VERSIONS table (block counts per version come from the QR standard).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use crypto.getRandomValues instead of Math.random for passwords?

    Math.random is not designed to resist prediction. getRandomValues uses the operating system's secure generator, which is what secrets require.
  2. 2. What problem does rejection sampling solve?

    Taking value % max slightly favours the small results unless the range divides 2^32 evenly. Discarding values from the uneven tail and drawing again makes every result equally likely.
  3. 3. Why is the QR matrix computed with useMemo keyed on text?

    Encoding does real work. useMemo reuses the previous result while text is unchanged, for example when only the surrounding component re-renders.
  4. 4. What is the job of error correction in a QR code?

    Reed-Solomon codewords add redundancy, so a scanner can reconstruct the data even if some modules are wrong or covered.

Summary

  • Use crypto.getRandomValues for secrets, and use rejection sampling so no character is favoured.
  • Entropy, strength labels and counters are derived from state; regenerate inside the event handler.
  • Wrap clipboard access in try/catch; previews and some browsers block it.
  • A QR code is a pipeline: bytes, Reed-Solomon error correction, fixed patterns, zigzag placement, masking.
  • Keep heavy logic in a pure function, memoize it, and render the result as SVG.

Next: Project: Blog App with Routing