Move One-Time Pad encryption to the browser (#479)

* Move One-Time Pad encryption to the browser; delete backend OTP module

OTP encryption/decryption is now performed entirely in the browser so
messages, keys, and generated pads never leave the originating device.

- Add app/src/components/otp.js: a JS port of the former modules/otp/lib.py
  (encrypt/decrypt, message formatting, validation, and secure pad
  generation via crypto.getRandomValues with rejection sampling).
- Encrypt/Decrypt now run live as the user types or pastes, with inline
  error messages instead of submit buttons.
- Generate New Pad builds the printable HTML locally (blob URL) instead of
  hitting /api/otp/html.
- Migrate all backend OTP tests to app/src/components/otp.test.js with
  identical data.
- Delete the modules/otp backend module and its blueprint registration.

* Revoke the One-Time Pad blob URL after the new tab loads

Addresses a minor blob-handle leak: handleGenerateNewPad created an object
URL on every click but never released it.

* Let users choose the One-Time Pad character set

Add an "Advanced" accordion under the buttons with three options: A-Z,
A-Z/0-9 (default, unchanged), and a custom character set. The chosen set is
shared by encrypt, decrypt, and pad generation.

- otp.js: parameterize encrypt/decrypt/generate on the alphabet (default
  OTP_CHARS for back-compat); add OTP_CHARS_ALPHA and validateCharset; input
  is auto-uppercased only when the set is all-uppercase, so custom sets with
  lowercase are case-sensitive; the printable pad is labeled with its set.
- Apps.js: lift charset state into OTP(); gate encrypt/decrypt/generate on a
  valid set with inline validation errors.
- otp.test.js: add A-Z, custom round-trip, auto-uppercase, validateCharset,
  and pad-label tests.

* Scope inverted-accordion dark background to direct children

The rule forcing #171616 on .ui.inverted.accordion .title/.content used a
descendant selector, so it leaked onto any nested element using the `content`
class — e.g. an ErrorMessage's Message.Content rendered inside SimpleAccordion
got a dark band behind its text. Scope to direct children so the accordion
still styles its own title/content but not nested components.

* Add optional error-detection checksum to the One-Time Pad

Adapts the position-weighted checksum from otp-checksum.md to the
frontend-only OTP. checksum = sum(position * value) mod N, parameterized on
the selected character set (N = chars.length), so it follows whichever pad
alphabet is chosen. Position weighting catches transposition errors.

- otp.js: add calculateChecksum/appendChecksum/verifyChecksum.
- Apps.js: opt-in "Append error-detection checksum" toggle in Advanced
  (default off). When on, encrypt appends a checksum char; decrypt verifies
  it, warns on mismatch, and still shows the decrypted text.
- otp.test.js: checksum unit tests, charset-variation, and end-to-end vectors.

* Show compact checksum status instead of a large warning box

Replace the bulky semantic-ui WarningMessage on decrypt with a small inline
status line: a green check + "Checksum is valid" or a red x + "Checksum is
invalid", shown whenever the checksum option is on and a message is being
decrypted.

* Fix checksum-mode decrypt truncating messages without a checksum

When the "Append error-detection checksum" option was on, Decrypt always
stripped the last ciphertext character before decrypting, so a message that
carried no trailing checksum (wrong sender setting, body pasted alone, etc.)
lost its final character and decrypted to garbage.

Add stripChecksum(received, chars), which removes the trailing character only
when it actually verifies as the checksum of the preceding characters; a
message without a valid checksum is returned intact and flagged invalid. The
decrypt UI now uses it.

Also broaden test coverage:
- stripChecksum tests, including a regression for the truncation bug.
- validation error classes (InvalidOTP/Plaintext/Ciphertext) and the
  longer-than-OTP length guards.
- deterministic encrypt/decrypt roundtrip fuzz across several character sets.
- generateMessage character-count and charset-membership checks.
- end-to-end checksummed encrypt -> format -> strip -> decrypt flow.

Use a dedicated InvalidMessage error for the checksum helpers instead of the
misleading InvalidPlaintext.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
lrnselfreliance 2026-06-13 13:52:18 -06:00 • committed by Roland
parent fb23fe1f61
commit 657a5bd561
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
16 changed files with 752 additions and 496 deletions

View file

@ -247,8 +247,10 @@ textarea.otp {
color: #DDDDDD !important;
}
.ui.inverted.accordion .title,
.ui.inverted.accordion .content {
/* Direct children only, so nested components that use the `content`/`title` class names (e.g. a Message's
Message.Content) are not given the accordion's dark background. */
.ui.inverted.accordion > .title,
.ui.inverted.accordion > .content {
background-color: #171616 !important;
}

View file

@ -7,7 +7,6 @@ import {
COLLECTIONS_API,
DEFAULT_LIMIT,
Downloaders,
OTP_API,
VIDEOS_API,
ZIM_API
} from "./components/Vars";
@ -584,39 +583,6 @@ export async function refreshChannel(channelId) {
}
return response;
}
export async function encryptOTP(otp, plaintext) {
let body = {otp, plaintext};
const response = await apiPost(`${OTP_API}/encrypt_otp`, body);
if (response.ok) {
return await response.json();
} else {
const message = await getErrorMessage(response, 'Failed to encrypt OTP. See server logs.');
toast({
type: 'error',
title: 'Failed to encrypt OTP',
description: message,
time: 5000,
})
}
}
export async function decryptOTP(otp, ciphertext) {
let body = {otp, ciphertext};
const response = await apiPost(`${OTP_API}/decrypt_otp`, body);
if (response.ok) {
return await response.json();
} else {
const message = await getErrorMessage(response, 'Failed to decrypt OTP. See server logs.');
toast({
type: 'error',
title: 'Failed to decrypt OTP',
description: message,
time: 5000,
})
}
}
export async function getCategories() {
const response = await apiGet(`${API_URI}/inventory/categories`);
if (response.ok) {

View file

@ -1,8 +1,11 @@
import React, {useContext} from 'react';
import React, {useContext, useState} from 'react';
import {
Checkbox,
Divider,
Icon,
Input,
Label,
Radio,
SegmentGroup,
StatisticLabel,
StatisticValue,
@ -10,136 +13,157 @@ import {
TableRow
} from "semantic-ui-react";
import {Link, Route, Routes} from "react-router";
import {decryptOTP, encryptOTP} from "../api";
import {
APIButton,
appendChecksum,
decryptOTP,
encryptOTP,
formatMessage,
generateHtml,
OTP_CHARS,
OTP_CHARS_ALPHA,
stripChecksum,
validateCharset
} from "./otp";
import {
ErrorMessage,
humanFileSize,
humanNumber,
mimetypeColor,
PageContainer,
SimpleAccordion,
toLocaleString,
useTitle
} from "./Common";
import {ThemeContext} from "../contexts/contexts";
import {Button, Header, Loader, Segment, Statistic, Table, TextArea} from "./Theme";
import {Button, Form, Header, Loader, Segment, Statistic, Table, TextArea} from "./Theme";
import {useStatistics, useVINDecoder} from "../hooks/customHooks";
import {CalculatorsPage} from "./Calculators";
class Encrypt extends React.Component {
constructor(props) {
super(props);
this.state = {
otp: '', plaintext: '', ciphertext: '',
function Encrypt({chars, checksum}) {
// Encrypt happens live as the user types or pastes. Nothing leaves the browser.
const [otp, setOtp] = useState('');
const [plaintext, setPlaintext] = useState('');
const handleInputChange = (event, {name, value}) => {
if (name === 'otp') {
setOtp(value);
} else {
setPlaintext(value);
}
};
let ciphertext = '';
let error = '';
if (otp && plaintext && chars) {
try {
const raw = encryptOTP(otp, plaintext, chars).ciphertext;
// When enabled, append a checksum character then re-group the whole message+checksum.
ciphertext = checksum ? formatMessage(appendChecksum(raw, chars)) : raw;
} catch (e) {
error = e.message;
}
}
handleSubmit = async () => {
let {otp, plaintext, ciphertext} = await encryptOTP(this.state.otp, this.state.plaintext);
this.setState({otp, plaintext, ciphertext});
}
handleInputChange = async (event, {name, value}) => {
this.setState({[name]: value});
}
render() {
const disabled = !(this.state.otp && this.state.plaintext);
return <>
<Header as='h2'>Encrypt</Header>
<SegmentGroup>
<Segment>
<h3>Key</h3>
<TextArea
name='otp'
className='otp'
value={this.state.otp}
onChange={this.handleInputChange}
placeholder='The random letters from your One-Time Pad'
/>
</Segment>
<Segment>
<h3>Plaintext</h3>
<TextArea
name='plaintext'
className='otp'
value={this.state.plaintext}
onChange={this.handleInputChange}
placeholder='The message you want to send'
/>
</Segment>
<Segment>
<h3>Ciphertext</h3>
<pre>{this.state.ciphertext || 'Enter your message above'}</pre>
</Segment>
</SegmentGroup>
<br/>
<APIButton
disabled={disabled}
onClick={this.handleSubmit}
>Encrypt</APIButton>
</>
}
return <>
<Header as='h2'>Encrypt</Header>
<SegmentGroup>
<Segment>
<h3>Key</h3>
<TextArea
name='otp'
className='otp'
value={otp}
onChange={handleInputChange}
placeholder='The random letters from your One-Time Pad'
/>
</Segment>
<Segment>
<h3>Plaintext</h3>
<TextArea
name='plaintext'
className='otp'
value={plaintext}
onChange={handleInputChange}
placeholder='The message you want to send'
/>
</Segment>
<Segment>
<h3>Ciphertext</h3>
{error
? <ErrorMessage>{error}</ErrorMessage>
: <pre>{ciphertext || (chars ? 'Enter your message above' : 'Set valid characters in Advanced options')}</pre>}
</Segment>
</SegmentGroup>
</>
}
class Decrypt extends React.Component {
constructor(props) {
super(props);
this.state = {
otp: '', plaintext: '', ciphertext: ''
function Decrypt({chars, checksum}) {
// Decrypt happens live as the user types or pastes. Nothing leaves the browser.
const [otp, setOtp] = useState('');
const [ciphertext, setCiphertext] = useState('');
const handleInputChange = (event, {name, value}) => {
if (name === 'otp') {
setOtp(value);
} else {
setCiphertext(value);
}
};
let plaintext = '';
let error = '';
let checksumValid = null; // null = not applicable (checksum off or nothing to check)
if (otp && ciphertext && chars) {
try {
let input = ciphertext;
if (checksum) {
// Only remove the trailing character when it actually verifies as a checksum, so a message without
// one is never silently truncated.
const {body, valid} = stripChecksum(ciphertext, chars);
checksumValid = valid;
input = body;
}
plaintext = decryptOTP(otp, input, chars).plaintext;
} catch (e) {
error = e.message;
}
}
handleSubmit = async () => {
let {otp, plaintext, ciphertext} = await decryptOTP(this.state.otp, this.state.ciphertext);
this.setState({otp, plaintext, ciphertext});
}
handleInputChange = async (event, {name, value}) => {
this.setState({[name]: value});
}
render() {
const disabled = !(this.state.otp && this.state.ciphertext);
return <>
<Header as='h2'>Decrypt</Header>
<SegmentGroup>
<Segment>
<h3>Key</h3>
<TextArea
name='otp'
className='otp'
value={this.state.otp}
onChange={this.handleInputChange}
placeholder='The random letters from your One-Time Pad'
/>
</Segment>
<Segment>
<h3>Ciphertext</h3>
<TextArea
name='ciphertext'
className='otp'
value={this.state.ciphertext}
onChange={this.handleInputChange}
placeholder='The message you received'
/>
</Segment>
<Segment>
<h3>Plaintext</h3>
<pre>{this.state.plaintext || 'Enter the encrypted message above'}</pre>
</Segment>
</SegmentGroup>
<br/>
<APIButton
disabled={disabled}
onClick={this.handleSubmit}
>Decrypt</APIButton>
</>
}
return <>
<Header as='h2'>Decrypt</Header>
<SegmentGroup>
<Segment>
<h3>Key</h3>
<TextArea
name='otp'
className='otp'
value={otp}
onChange={handleInputChange}
placeholder='The random letters from your One-Time Pad'
/>
</Segment>
<Segment>
<h3>Ciphertext</h3>
<TextArea
name='ciphertext'
className='otp'
value={ciphertext}
onChange={handleInputChange}
placeholder='The message you received'
/>
</Segment>
<Segment>
<h3>Plaintext</h3>
{checksumValid !== null && <p>
<Icon name={checksumValid ? 'check' : 'times'} color={checksumValid ? 'green' : 'red'}/>
{checksumValid ? 'Checksum is valid' : 'Checksum is invalid'}
</p>}
{error
? <ErrorMessage>{error}</ErrorMessage>
: <pre>{plaintext || (chars ? 'Enter the encrypted message above' : 'Set valid characters in Advanced options')}</pre>}
</Segment>
</SegmentGroup>
</>
}
function OTP() {
@ -147,22 +171,78 @@ function OTP() {
const {t} = useContext(ThemeContext);
let newPadURL = `https://${window.location.host}/api/otp/html`;
// The character set is a property of the pad: encrypt, decrypt, and generation all use the same alphabet.
const [charsetKind, setCharsetKind] = useState('alphanumeric'); // 'alpha' | 'alphanumeric' | 'custom'
const [customChars, setCustomChars] = useState('');
const charsetError = charsetKind === 'custom' ? validateCharset(customChars) : null;
const chars = charsetKind === 'alpha' ? OTP_CHARS_ALPHA
: charsetKind === 'custom' ? customChars
: OTP_CHARS;
// A null charset means the custom set is not yet usable; encrypt/decrypt/generate are gated on this.
const activeChars = charsetError ? null : chars;
// Optional error-detection checksum appended to the ciphertext.
const [checksum, setChecksum] = useState(false);
let cheatSheetURL = `${process.env.PUBLIC_URL}/one-time-pad-cheat-sheet.pdf`;
// Generate a new One-Time Pad entirely in the browser and open it in a new tab so it can be printed. The pad is
// never sent to or stored on the server.
const handleGenerateNewPad = () => {
const blob = new Blob([generateHtml(activeChars)], {type: 'text/html'});
const url = URL.createObjectURL(blob);
window.open(url, '_blank');
// Release the blob handle once the new tab has had time to load it.
setTimeout(() => URL.revokeObjectURL(url), 60000);
};
return <>
<Header as='h1'>One-Time Pad</Header>
<Header as='h4'>One-Time Pads can be used to encrypt your communications. This can be done by hand
(yes, really) or in this app.</Header>
<p {...t}>These messages are never stored and cannot be retrieved.</p>
<Button color='violet' href={newPadURL}>Generate New Pad</Button>
<Button color='violet' disabled={!activeChars} onClick={handleGenerateNewPad}>Generate New Pad</Button>
<Button secondary href={cheatSheetURL}>Cheat Sheet PDF</Button>
<Divider/>
<Encrypt/>
<SimpleAccordion title='Advanced'>
<Header as='h4'>Pad characters</Header>
<Form>
<Form.Field>
<Radio label='A–Z' name='charset' value='alpha'
checked={charsetKind === 'alpha'} onChange={() => setCharsetKind('alpha')}/>
</Form.Field>
<Form.Field>
<Radio label='A–Z and 0–9' name='charset' value='alphanumeric'
checked={charsetKind === 'alphanumeric'} onChange={() => setCharsetKind('alphanumeric')}/>
</Form.Field>
<Form.Field>
<Radio label='Custom' name='charset' value='custom'
checked={charsetKind === 'custom'} onChange={() => setCharsetKind('custom')}/>
</Form.Field>
</Form>
{charsetKind === 'custom' && <>
<Input
fluid
value={customChars}
placeholder='e.g. ABCDEF0123'
onChange={(e, {value}) => setCustomChars(value)}
/>
{charsetError && <ErrorMessage>{charsetError}</ErrorMessage>}
</>}
<Header as='h4'>Error detection</Header>
<Checkbox
label='Append error-detection checksum'
checked={checksum}
onChange={() => setChecksum(!checksum)}
/>
</SimpleAccordion>
<Divider/>
<Decrypt/>
<Encrypt chars={activeChars} checksum={checksum}/>
<Divider/>
<Decrypt chars={activeChars} checksum={checksum}/>
</>
}
@ -353,4 +433,4 @@ export function MoreRoute(props) {
export function ColoredInput({name, value, label, color, ...props}) {
label = label ? <Label color={color}>{label}</Label> : null;
return <Input value={value} name={name} label={label} {...props}/>
}
}

View file

@ -2,7 +2,6 @@ export const API_URI = process.env && process.env.REACT_APP_API_URI ? process.en
export const VIDEOS_API = `${API_URI}/videos`;
export const ARCHIVES_API = `${API_URI}/archive`;
export const COLLECTIONS_API = `${API_URI}/collections`;
export const OTP_API = `${API_URI}/otp`;
export const ZIM_API = `${API_URI}/zim`;
export const DEFAULT_LIMIT = 20;
export const NAME = process.env && process.env.REACT_APP_NAME ? process.env.REACT_APP_NAME : null;

251
app/src/components/otp.js Normal file
View file

@ -0,0 +1,251 @@
// One-Time Pad encryption/decryption. This is performed entirely in the browser; messages are never sent to the
// server. This is a JavaScript port of the original Python implementation (modules/otp/lib.py).
// The default character set: letters and digits.
export const OTP_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
// A letters-only character set, easiest to work by hand.
export const OTP_CHARS_ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// The number of characters in each group, separated by spaces.
export const GROUP_SIZE = 5;
// The groups in each row of a message, separated by newlines. This is small to allow for mobile phones.
export const GROUP_COUNT = 5;
const WHITESPACE = /\s/g;
// A character set whose characters are all uppercase can have its input auto-uppercased for convenience. A custom
// set containing lowercase is treated case-sensitively (the input is used verbatim).
const shouldUppercase = (chars) => chars === chars.toUpperCase();
export class InvalidOTP extends Error {
constructor(message = 'OTP has invalid characters') {
super(message);
this.name = 'InvalidOTP';
}
}
export class InvalidPlaintext extends Error {
constructor(message = 'Plaintext has invalid characters') {
super(message);
this.name = 'InvalidPlaintext';
}
}
export class InvalidCiphertext extends Error {
constructor(message = 'Ciphertext has invalid characters') {
super(message);
this.name = 'InvalidCiphertext';
}
}
export class InvalidMessage extends Error {
constructor(message = 'Message has invalid characters') {
super(message);
this.name = 'InvalidMessage';
}
}
// Split an iterable into chunks of the defined size.
function chunks(it, size) {
const result = [];
for (let i = 0; i < it.length; i += size) {
result.push(it.slice(i, i + size));
}
return result;
}
// Formats messages in the style of a One-Time-Pad. Usually 5 characters per group.
//
// formatMessage('SOMEMESSAGE') === 'SOMEM ESSAG E'
export function formatMessage(message, groupCount = GROUP_COUNT) {
const groups = chunks(message, GROUP_SIZE);
const rows = chunks(groups, groupCount);
return rows.map(row => row.join(' ')).join('\n');
}
function validateMessage(message, ErrorClass, chars) {
if (shouldUppercase(chars)) {
message = message.toUpperCase();
}
message = message.replace(WHITESPACE, '');
for (const char of message) {
if (!chars.includes(char)) {
throw new ErrorClass();
}
}
return message;
}
function encryptChar(plaintext, otp, chars) {
const calculated = (chars.indexOf(plaintext) + chars.indexOf(otp)) % chars.length;
return chars[calculated];
}
function decryptChar(ciphertext, otp, chars) {
// JavaScript's % can return negative values; add chars.length before the modulo to keep it positive.
const calculated = (chars.indexOf(ciphertext) - chars.indexOf(otp) + chars.length) % chars.length;
return chars[calculated];
}
// Validate a character set. Returns an error message string, or null when the set is usable.
export function validateCharset(chars) {
if (!chars || chars.length < 2) {
return 'Enter at least 2 characters';
}
if (chars.length > 256) {
return 'Too many characters (max 256)';
}
if (/\s/.test(chars)) {
return 'Characters cannot contain spaces';
}
if (new Set(chars).size !== chars.length) {
return 'Characters must be unique';
}
return null;
}
// Encrypt a plaintext message using an OTP and the given character set.
export function encryptOTP(otp, plaintext, chars = OTP_CHARS) {
otp = validateMessage(otp, InvalidOTP, chars);
plaintext = validateMessage(plaintext, InvalidPlaintext, chars);
if (plaintext.length > otp.length) {
throw new InvalidPlaintext('Plaintext is longer than OTP');
}
let ciphertext = '';
for (let i = 0; i < plaintext.length; i++) {
ciphertext += encryptChar(plaintext[i], otp[i], chars);
}
return {
ciphertext: formatMessage(ciphertext),
otp: formatMessage(otp),
plaintext: formatMessage(plaintext),
};
}
// Decrypt an encrypted message that was encrypted with an OTP and the given character set.
export function decryptOTP(otp, ciphertext, chars = OTP_CHARS) {
otp = validateMessage(otp, InvalidOTP, chars);
ciphertext = validateMessage(ciphertext, InvalidCiphertext, chars);
if (ciphertext.length > otp.length) {
throw new InvalidCiphertext('Ciphertext is longer than OTP');
}
let plaintext = '';
for (let i = 0; i < ciphertext.length; i++) {
plaintext += decryptChar(ciphertext[i], otp[i], chars);
}
return {
plaintext: formatMessage(plaintext),
ciphertext: formatMessage(ciphertext),
otp: formatMessage(otp),
};
}
// Calculate a position-weighted checksum character for a message: sum(position * value) mod N, where position is
// 1-indexed and value is the character's index in the set. Position weighting catches transposition errors.
export function calculateChecksum(message, chars = OTP_CHARS) {
message = validateMessage(message, InvalidMessage, chars);
let total = 0;
for (let i = 0; i < message.length; i++) {
total += (i + 1) * chars.indexOf(message[i]);
}
return chars[total % chars.length];
}
// Append a checksum character to a message.
export function appendChecksum(message, chars = OTP_CHARS) {
message = validateMessage(message, InvalidMessage, chars);
return message + calculateChecksum(message, chars);
}
// Verify a message whose last character is a checksum. Returns true when the checksum matches.
export function verifyChecksum(messageWithChecksum, chars = OTP_CHARS) {
messageWithChecksum = validateMessage(messageWithChecksum, InvalidMessage, chars);
if (messageWithChecksum.length < 2) {
return false;
}
return calculateChecksum(messageWithChecksum.slice(0, -1), chars) === messageWithChecksum.slice(-1);
}
// Interpret a received message that may carry a trailing checksum character. The last character is removed ONLY when
// it verifies as the checksum of the preceding characters; otherwise the message is returned unchanged. This avoids
// silently truncating a legitimate character from a message that does not actually carry a checksum.
// Returns {body, valid}: `body` is the message to decrypt, `valid` is whether a checksum was present and matched.
export function stripChecksum(received, chars = OTP_CHARS) {
const cleaned = validateMessage(received, InvalidMessage, chars);
if (cleaned.length >= 2 && calculateChecksum(cleaned.slice(0, -1), chars) === cleaned.slice(-1)) {
return {body: cleaned.slice(0, -1), valid: true};
}
return {body: cleaned, valid: false};
}
function getCrypto() {
const cryptoObj = typeof window !== 'undefined' && window.crypto;
if (!cryptoObj || !cryptoObj.getRandomValues) {
throw new Error('A cryptographically secure random number generator is not available.');
}
return cryptoObj;
}
// Choose a single OTP character using a cryptographically secure RNG. Rejection sampling is used to avoid modulo bias.
function generateChar(chars) {
const cryptoObj = getCrypto();
const max = 256 - (256 % chars.length);
const buffer = new Uint8Array(1);
let value;
do {
cryptoObj.getRandomValues(buffer);
value = buffer[0];
} while (value >= max);
return chars[value % chars.length];
}
// Create an OTP message. Format it for ease of use.
export function generateMessage(chars = OTP_CHARS) {
let message = '';
// Use 16 groups per line because this page will be printed.
for (let i = 0; i < 320; i++) {
message += generateChar(chars);
}
return formatMessage(message, 16);
}
const PAGE_HTML = `
<html>
<title>One Time Pad - Unique, just for you</title>
<style>
/* Remove decoration from links so they are readable when printed */
a { text-decoration: none; }
</style>
<body>
<pre>Characters: {chars}</pre>
{messages}
Print this page and distribute the copies (along with the <a href="https://lrnsr.co/aY6m">One Time Pad Cheat Sheet
https://lrnsr.co/aY6m</a>) to all members of your group that you trust to receive your encrypted messages. Every
person must have their OWN copy of this "One Time Pad" to encrypt and decrypt messages.
<br>
<b>Use each message ONLY ONCE.</b> Cut off and burn each message from this paper as it is used.
<br>
To learn how to use this page, please visit: <a href="https://lrnsr.co/H7Za">https://lrnsr.co/H7Za</a>
</body>
</html>
`;
// Create an HTML One-Time Pad page. This page will have instructions on how to use the OTP.
export function generateHtml(chars = OTP_CHARS) {
const messages = [];
for (let i = 1; i <= 8; i++) {
messages.push(`<pre>MESSAGE ${i}</pre><pre>${generateMessage(chars)}</pre>`);
}
// Use function replacers so a '$' in a custom character set is not treated as a replacement pattern.
return PAGE_HTML.replace('{messages}', () => messages.join('\n\n')).replace('{chars}', () => chars);
}

View file

@ -0,0 +1,301 @@
import {webcrypto} from 'crypto';
import {
appendChecksum,
calculateChecksum,
decryptOTP,
encryptOTP,
formatMessage,
generateHtml,
generateMessage,
InvalidCiphertext,
InvalidOTP,
InvalidPlaintext,
OTP_CHARS,
OTP_CHARS_ALPHA,
stripChecksum,
validateCharset,
verifyChecksum
} from './otp';
// jsdom does not always provide window.crypto; real browsers always do. Polyfill it for the generation tests.
if (!window.crypto || !window.crypto.getRandomValues) {
window.crypto = webcrypto;
}
// These cases are migrated from the original backend tests (modules/otp/test/test_otp.py and test_api.py); the
// expected data is identical so the browser implementation matches the old server behavior exactly.
describe('encryptOTP', () => {
test.each([
['', '', ''],
['A', 'A', 'A'],
['B', 'B', 'C'],
['9', '9', '8'],
['W', 'H', '3'],
['W8JD7', 'HELLO', '3CUOL'],
['XMCKL', 'HELLO', '4QNVZ'],
[
// This message says: TEST THE ENCRYPTION OF A LONG MESSAGE THE SPACES SHOULDNT MATTER
// The message is shorter than the OTP, this is fine. The ciphertext should be the same
// length as the message.
'V4YPT RCJLZ QZVSD 0U2E6 OOKNU\nZDH8F 4XQ76 OR6EK J0TRG 0G0HU\nS4BUJ',
'TESTT HEENC RYPTI ONOFA LONGM\nESSAG ETHES PACES SHOUL DNTMA\nTTER',
'E8G8C YGNY1 7NABL E7GJ6 Z2XT6\n3VZ8L 8GXBO 3R8I2 177BR 3TJTU\nBNFB',
],
// From the original API test (test_api.py).
['asdf', 'asdf', 'AAGK'],
])('encrypts otp=%j plaintext=%j', (otp, plaintext, ciphertext) => {
const result = encryptOTP(otp, plaintext);
expect(result).toEqual({
otp: formatMessage(otp.toUpperCase().replace(/\s/g, '')),
plaintext: formatMessage(plaintext.toUpperCase().replace(/\s/g, '')),
ciphertext,
});
// Whitespace is ignored.
const paddedPlaintext = `\t ${plaintext}`;
const paddedOtp = `\n ${otp} `;
const paddedResult = encryptOTP(paddedOtp, paddedPlaintext);
expect(paddedResult).toEqual({
otp: formatMessage(otp.toUpperCase().replace(/\s/g, '')),
plaintext: formatMessage(plaintext.toUpperCase().replace(/\s/g, '')),
ciphertext,
});
});
});
describe('decryptOTP', () => {
test.each([
['', '', ''],
['A', 'A', 'A'],
['B', 'C', 'B'],
['W', '3', 'H'],
['9', '8', '9'],
['W8JD7', '3CUOL', 'HELLO'],
['XMCKL', '4QNVZ', 'HELLO'],
[
'V4YPT RCJLZ QZVSD 0U2E6 OOKNU\nZDH8F 4XQ76 OR6EK J0TRG 0G0HU\nS4BUJ',
'E8G8C YGNY1 7NABL E7GJ6 Z2XT6\n3VZ8L 8GXBO 3R8I2 177BR 3TJTU\nBNFB',
'TESTT HEENC RYPTI ONOFA LONGM\nESSAG ETHES PACES SHOUL DNTMA\nTTER',
],
// From the original API test (test_api.py).
['asdf', 'aagk', 'ASDF'],
])('decrypts otp=%j ciphertext=%j', (otp, ciphertext, plaintext) => {
const result = decryptOTP(otp, ciphertext);
expect(result).toEqual({
otp: formatMessage(otp.toUpperCase().replace(/\s/g, '')),
ciphertext: formatMessage(ciphertext.toUpperCase().replace(/\s/g, '')),
plaintext,
});
});
});
describe('formatMessage', () => {
test.each([
['ABC', 'ABC'],
['ABCDEFG', 'ABCDE FG'],
['SOMEMESSAGE', 'SOMEM ESSAG E'],
[
'ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890',
'ABCDE FGHIJ KLMNO PQRST UVWXY\nZ0123 45678 90',
],
[
'A'.repeat(94),
'AAAAA AAAAA AAAAA AAAAA AAAAA\n' +
'AAAAA AAAAA AAAAA AAAAA AAAAA\n' +
'AAAAA AAAAA AAAAA AAAAA AAAAA\n' +
'AAAAA AAAAA AAAAA AAAA',
],
])('formats %j', (message, expected) => {
expect(formatMessage(message)).toEqual(expected);
});
});
describe('custom character sets', () => {
test('A–Z only encrypts with the classic Vigenère vector', () => {
// With 0–9 absent (mod 26), HELLO + XMCKL = EQNVZ — different from the 36-char result.
const result = encryptOTP('XMCKL', 'HELLO', OTP_CHARS_ALPHA);
expect(result.ciphertext).toEqual('EQNVZ');
expect(decryptOTP('XMCKL', 'EQNVZ', OTP_CHARS_ALPHA).plaintext).toEqual('HELLO');
});
test('a digit is rejected when the set is A–Z only', () => {
expect(() => encryptOTP('ABCDE', 'HELL0', OTP_CHARS_ALPHA)).toThrow('Plaintext has invalid characters');
});
test('round-trips through a custom numeric set', () => {
const chars = '0123456789';
const {ciphertext} = encryptOTP('48271', '13579', chars);
expect(decryptOTP('48271', ciphertext, chars).plaintext).toEqual('13579');
});
test('an out-of-set character throws', () => {
expect(() => encryptOTP('01234', 'ABCDE', '0123456789')).toThrow('Plaintext has invalid characters');
});
test('an all-uppercase custom set auto-uppercases input', () => {
// The set is all uppercase, so lowercase input is folded to uppercase (like the built-in sets).
const chars = 'ABCDEF';
expect(encryptOTP('aabbcc', 'abcdef', chars)).toEqual(encryptOTP('AABBCC', 'ABCDEF', chars));
});
test('a custom set with lowercase is case-sensitive', () => {
// The set contains lowercase, so input is used verbatim; uppercase input is not in the set.
expect(encryptOTP('abcde', 'abcde', 'abcde').ciphertext).toBeTruthy();
expect(() => encryptOTP('abcde', 'ABCDE', 'abcde')).toThrow('Plaintext has invalid characters');
});
});
describe('validateCharset', () => {
test.each([
['ABCDEFGHIJKLMNOPQRSTUVWXYZ', null],
['0123456789', null],
['', 'Enter at least 2 characters'],
['A', 'Enter at least 2 characters'],
['AABC', 'Characters must be unique'],
['AB CD', 'Characters cannot contain spaces'],
['A'.repeat(257), 'Too many characters (max 256)'],
])('validates %j', (chars, expected) => {
expect(validateCharset(chars)).toEqual(expected);
});
});
describe('checksum', () => {
// Vectors adapted from the original backend plan (otp-checksum.md), default 36-char set.
test.each([
['', 'A'],
['A', 'A'],
['B', 'B'],
['HELLO', 'S'], // 7+8+33+44+70 = 162 mod 36 = 18 = 'S'
['HLELO', 'L'], // transposition produces a different checksum (162→155, 155 mod 36 = 11 = 'L')
])('calculateChecksum(%j) = %j', (message, expected) => {
expect(calculateChecksum(message)).toEqual(expected);
});
test.each([
['HELLOS', true],
['HELLOX', false], // wrong checksum
['HLELOS', false], // transposed message, original checksum
])('verifyChecksum(%j) = %j', (messageWithChecksum, expected) => {
expect(verifyChecksum(messageWithChecksum)).toEqual(expected);
});
test('appendChecksum adds the checksum character', () => {
expect(appendChecksum('HELLO')).toEqual('HELLOS');
});
test('checksum follows the character set', () => {
// With A–Z (mod 26): 162 mod 26 = 6 = 'G', not 'S'.
expect(calculateChecksum('HELLO', OTP_CHARS_ALPHA)).toEqual('G');
});
test('checksum protects an encrypted message end-to-end', () => {
const {ciphertext} = encryptOTP('W8JD7', 'HELLO'); // '3CUOL'
expect(appendChecksum(ciphertext)).toEqual('3CUOLY');
// A transposition in the ciphertext yields a different checksum.
expect(calculateChecksum('3UCOL')).not.toEqual(calculateChecksum('3CUOL'));
});
});
describe('validation errors', () => {
test('an invalid OTP character throws InvalidOTP', () => {
expect(() => encryptOTP('A!', 'AB')).toThrow(InvalidOTP);
expect(() => decryptOTP('A!', 'AB')).toThrow(InvalidOTP);
});
test('an invalid plaintext character throws InvalidPlaintext', () => {
expect(() => encryptOTP('ABC', 'A!')).toThrow(InvalidPlaintext);
});
test('an invalid ciphertext character throws InvalidCiphertext', () => {
expect(() => decryptOTP('ABC', 'A!')).toThrow(InvalidCiphertext);
});
test('plaintext longer than the OTP throws', () => {
expect(() => encryptOTP('AB', 'ABC')).toThrow('Plaintext is longer than OTP');
});
test('ciphertext longer than the OTP throws', () => {
expect(() => decryptOTP('AB', 'ABC')).toThrow('Ciphertext is longer than OTP');
});
});
describe('encrypt/decrypt roundtrip', () => {
// A small deterministic PRNG keeps the fuzz reproducible (no reliance on Math.random/crypto).
let seed = 123456789;
const rand = () => {
seed = (seed * 1103515245 + 12345) & 0x7fffffff;
return seed / 0x7fffffff;
};
const pick = (chars, n) => {
let out = '';
for (let i = 0; i < n; i++) out += chars[Math.floor(rand() * chars.length)];
return out;
};
test.each([
OTP_CHARS_ALPHA,
OTP_CHARS,
'0123456789',
'abcdef0123', // mixed-case-safe custom set (lowercase => case-sensitive, no uppercasing)
])('recovers the plaintext over %j', (chars) => {
for (let n = 0; n < 50; n++) {
const len = 1 + Math.floor(rand() * 20);
const plaintext = pick(chars, len);
const otp = pick(chars, len + Math.floor(rand() * 10)); // OTP at least as long as the message
const {ciphertext} = encryptOTP(otp, plaintext, chars);
expect(decryptOTP(otp, ciphertext, chars).plaintext).toEqual(formatMessage(plaintext));
}
});
});
describe('stripChecksum', () => {
test('removes a valid trailing checksum', () => {
// calculateChecksum('HELLO') === 'S'
expect(stripChecksum('HELLOS')).toEqual({body: 'HELLO', valid: true});
});
test('does NOT truncate a message that has no valid checksum', () => {
// Regression: with the checksum option on, the UI used to blindly drop the last character. 'HELLO' has no
// checksum (its checksum would be 'S'), so it must be returned intact rather than decoded as 'HELL'.
expect(stripChecksum('HELLO')).toEqual({body: 'HELLO', valid: false});
});
test('leaves a corrupted checksummed message intact and flags it invalid', () => {
expect(stripChecksum('HELLOX')).toEqual({body: 'HELLOX', valid: false});
});
test('mirrors the decrypt UI flow end-to-end', () => {
const otp = 'W8JD7';
const raw = encryptOTP(otp, 'HELLO').ciphertext; // '3CUOL'
const transmitted = formatMessage(appendChecksum(raw)); // '3CUOL Y'
const {body, valid} = stripChecksum(transmitted);
expect(valid).toBe(true);
expect(decryptOTP(otp, body).plaintext).toEqual('HELLO');
});
});
describe('generateMessage', () => {
test('produces 320 characters from the default set', () => {
const message = generateMessage().replace(/\s/g, '');
expect(message).toHaveLength(320);
expect([...message].every(c => OTP_CHARS.includes(c))).toBe(true);
});
test('only uses the given character set', () => {
const chars = 'AB';
const message = generateMessage(chars).replace(/\s/g, '');
expect(message).toHaveLength(320);
expect([...message].every(c => chars.includes(c))).toBe(true);
});
});
describe('generateHtml', () => {
test('generates a OTP HTML page', () => {
expect(generateHtml()).toBeTruthy();
});
test('labels the page with the character set it used', () => {
expect(generateHtml(OTP_CHARS_ALPHA)).toContain('Characters: ABCDEFGHIJKLMNOPQRSTUVWXYZ');
});
});

View file

@ -2,6 +2,5 @@ from .archive import api
from .docs import api
from .inventory import api
from .map import api
from .otp import api
from .videos import api
from .zim import api, test

View file

@ -1,36 +0,0 @@
from sanic import response, Blueprint
from sanic.request import Request
from sanic_ext import validate
from sanic_ext.extensions.openapi import openapi
from . import lib, schema
otp_bp = Blueprint('OTP', '/api/otp')
@otp_bp.post('/encrypt_otp')
@openapi.definition(
summary='Encrypt a message with OTP.',
body=schema.EncryptOTPRequest,
)
@validate(schema.EncryptOTPRequest)
async def post_encrypt_otp(_: Request, body: schema.EncryptOTPRequest):
data = lib.encrypt_otp(body.otp, body.plaintext)
return response.json(data)
@otp_bp.post('/decrypt_otp')
@openapi.definition(
summary='Decrypt a message with OTP.',
body=schema.DecryptOTPRequest,
)
@validate(schema.DecryptOTPRequest)
async def post_decrypt_otp(_: Request, body: schema.DecryptOTPRequest):
data = lib.decrypt_otp(body.otp, body.ciphertext)
return response.json(data)
@otp_bp.get('/html')
async def get_new_otp_html(_: Request):
body = lib.generate_html()
return response.html(body)

View file

@ -1,21 +0,0 @@
from http import HTTPStatus
from wrolpi.errors import APIError
class InvalidOTP(APIError):
code = 'INVALID_OTP'
summary = 'OTP has invalid characters'
status_code = HTTPStatus.BAD_REQUEST
class InvalidPlaintext(APIError):
code = 'INVALID_PLAINTEXT'
summary = 'Plaintext has invalid characters'
status_code = HTTPStatus.BAD_REQUEST
class InvalidCiphertext(APIError):
code = 'INVALID_CIPHERTEXT'
summary = 'Ciphertext has invalid characters'
status_code = HTTPStatus.BAD_REQUEST

View file

@ -1,135 +0,0 @@
import secrets
from functools import partial
from typing import Dict
from modules.otp.errors import InvalidOTP, InvalidPlaintext, InvalidCiphertext
from wrolpi.common import chunks, remove_whitespace, logger
# These are the only characters we support.
logger = logger.getChild(__name__)
OTP_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
# The number of characters in each group, separated by spaces.
GROUP_SIZE = 5
# The groups in each row of a message, separated by newlines. This is small to allow for mobile phones.
GROUP_COUNT = 5
def format_message(message: str, group_count: int = GROUP_COUNT) -> str:
"""
Formats messages in the style of a One-Time-Pad. Usually 5 characters per group.
>>> format_message('SOMEMESSAGE')
'SOMEM ESSAG E'
"""
groups = [''.join(i) for i in chunks(message, GROUP_SIZE)]
rows = chunks(groups, group_count)
message = '\n'.join(' '.join(group for group in groups) for groups in rows)
return message
generate_char = partial(secrets.choice, OTP_CHARS)
def generate_message():
"""
Create a OTP message. Format it for ease of use.
"""
# Use 20 messages per line because this page will be printed.
return format_message(''.join(generate_char() for _ in range(320)), 16)
PAGE_HTML = '''
<html>
<title>One Time Pad - Unique, just for you</title>
<style>
/* Remove decoration from links so they are readable when printed */
a {{ text-decoration: none; }} // escaped for python
</style>
<body>
{messages}
Print this page and distribute the copies (along with the <a href="https://lrnsr.co/aY6m">One Time Pad Cheat Sheet
https://lrnsr.co/aY6m</a>) to all members of your group that you trust to receive your encrypted messages. Every
person must have their OWN copy of this "One Time Pad" to encrypt and decrypt messages.
<br>
<b>Use each message ONLY ONCE.</b> Cut off and burn each message from this paper as it is used.
<br>
To learn how to use this page, please visit: <a href="https://lrnsr.co/H7Za">https://lrnsr.co/H7Za</a>
</body>
</html>
'''
def generate_html() -> str:
"""
Create an HTML One-Time Pad page. This page will have instructions on how to use the OTP.
"""
messages = [generate_message() for _ in range(8)]
messages = '\n\n'.join(f'<pre>MESSAGE {i}</pre><pre>{j}</pre>' for i, j in enumerate(messages, 1))
return PAGE_HTML.format(messages=messages)
def validate_message(otp, error_class):
otp = otp.upper()
otp = remove_whitespace(otp)
if not all(i in OTP_CHARS for i in otp):
raise error_class()
return otp
CHARS_LEN = len(OTP_CHARS)
def encrypt_char(plaintext: str, otp: str) -> str:
calculated = (OTP_CHARS.index(plaintext) + OTP_CHARS.index(otp)) % CHARS_LEN
return OTP_CHARS[calculated]
def decrypt_char(ciphertext: str, otp: str) -> str:
calculated = (OTP_CHARS.index(ciphertext) - OTP_CHARS.index(otp)) % CHARS_LEN
return OTP_CHARS[calculated]
def encrypt_otp(otp: str, plaintext: str) -> Dict[str, str]:
"""
Encrypt a plaintext message using an OTP.
"""
otp = validate_message(otp, InvalidOTP)
plaintext = validate_message(plaintext, InvalidPlaintext)
if len(plaintext) > len(otp):
raise InvalidPlaintext('Plaintext is longer than OTP')
ciphertext = ''.join(encrypt_char(p, o) for p, o in zip(plaintext, otp))
data = dict(
ciphertext=format_message(ciphertext),
otp=format_message(otp),
plaintext=format_message(plaintext),
)
return data
def decrypt_otp(otp: str, ciphertext: str) -> Dict[str, str]:
"""
Decrypt an encrypted message that was encrypted with an OTP.
"""
otp = validate_message(otp, InvalidOTP)
ciphertext = validate_message(ciphertext, InvalidCiphertext)
if len(ciphertext) > len(otp):
raise InvalidCiphertext('Ciphertext is longer than OTP')
plaintext = ''.join(decrypt_char(c, o) for c, o in zip(ciphertext, otp))
data = dict(
plaintext=format_message(plaintext),
ciphertext=format_message(ciphertext),
otp=format_message(otp),
)
return data

View file

@ -1,13 +0,0 @@
from dataclasses import dataclass
@dataclass
class EncryptOTPRequest:
otp: str
plaintext: str
@dataclass
class DecryptOTPRequest:
otp: str
ciphertext: str

View file

@ -1,34 +0,0 @@
import json
from http import HTTPStatus
import pytest
@pytest.mark.asyncio
async def test_encrypt(async_client):
body = dict(otp='asdf', plaintext='asdf')
request, response = await async_client.post('/api/otp/encrypt_otp', content=json.dumps(body))
assert response.status_code == HTTPStatus.OK
assert response.json == dict(
ciphertext='AAGK',
otp='ASDF',
plaintext='ASDF',
)
@pytest.mark.asyncio
async def test_decrypt(async_client):
body = dict(otp='asdf', ciphertext='aagk')
request, response = await async_client.post('/api/otp/decrypt_otp', content=json.dumps(body))
assert response.status_code == HTTPStatus.OK
assert response.json == dict(
ciphertext='AAGK',
otp='ASDF',
plaintext='ASDF',
)
@pytest.mark.asyncio
async def test_get_html(async_client):
request, response = await async_client.get('/api/otp/html')
assert response.status_code == HTTPStatus.OK

View file

@ -1,101 +0,0 @@
import pytest
from modules.otp import lib
@pytest.mark.parametrize(
'otp,plaintext,ciphertext',
[
('', '', ''),
('A', 'A', 'A'),
('B', 'B', 'C'),
('9', '9', '8'),
('W', 'H', '3'),
('W', 'H', '3'),
('W8JD7', 'HELLO', '3CUOL'),
('XMCKL', 'HELLO', '4QNVZ'),
(
# This message says: TEST THE ENCRYPTION OF A LONG MESSAGE THE SPACES SHOULDNT MATTER
# The message is shorter than the OTP, this is fine. The ciphertext should be the same
# length as the message.
'V4YPT RCJLZ QZVSD 0U2E6 OOKNU\nZDH8F 4XQ76 OR6EK J0TRG 0G0HU\nS4BUJ',
'TESTT HEENC RYPTI ONOFA LONGM\nESSAG ETHES PACES SHOUL DNTMA\nTTER',
'E8G8C YGNY1 7NABL E7GJ6 Z2XT6\n3VZ8L 8GXBO 3R8I2 177BR 3TJTU\nBNFB'
),
],
)
def test_encrypt_otp(otp, plaintext, ciphertext):
result = lib.encrypt_otp(otp, plaintext)
expected = dict(
otp=otp,
plaintext=plaintext,
ciphertext=ciphertext,
)
assert result == expected
# Whitespace is ignored
plaintext = f'\t {plaintext}'
otp = f'\n {otp} '
result = lib.encrypt_otp(otp, plaintext)
expected = dict(
otp=otp.strip(),
plaintext=plaintext.strip(),
ciphertext=ciphertext,
)
assert result == expected
@pytest.mark.parametrize(
'otp,ciphertext,plaintext',
[
('', '', ''),
('A', 'A', 'A'),
('B', 'C', 'B'),
('W', '3', 'H'),
('9', '8', '9'),
('W8JD7', '3CUOL', 'HELLO'),
('XMCKL', '4QNVZ', 'HELLO'),
(
'V4YPT RCJLZ QZVSD 0U2E6 OOKNU\nZDH8F 4XQ76 OR6EK J0TRG 0G0HU\nS4BUJ',
'E8G8C YGNY1 7NABL E7GJ6 Z2XT6\n3VZ8L 8GXBO 3R8I2 177BR 3TJTU\nBNFB',
'TESTT HEENC RYPTI ONOFA LONGM\nESSAG ETHES PACES SHOUL DNTMA\nTTER',
),
],
)
def test_decrypt_otp(otp, ciphertext, plaintext):
result = lib.decrypt_otp(otp, ciphertext)
expected = dict(
otp=otp,
plaintext=plaintext,
ciphertext=ciphertext,
)
assert result == expected
@pytest.mark.parametrize(
'message,expected',
[
('ABC', 'ABC'),
('ABCDEFG', 'ABCDE FG'),
('SOMEMESSAGE', 'SOMEM ESSAG E'),
(
'ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890',
'ABCDE FGHIJ KLMNO PQRST UVWXY\nZ0123 45678 90',
),
(
''.join('A' for _ in range(94)),
'AAAAA AAAAA AAAAA AAAAA AAAAA\n'
'AAAAA AAAAA AAAAA AAAAA AAAAA\n'
'AAAAA AAAAA AAAAA AAAAA AAAAA\n'
'AAAAA AAAAA AAAAA AAAA'
),
]
)
def test_format_message(message, expected):
result = lib.format_message(message)
assert result == expected
def test_get_new_otp_html():
"""Generate a OTP HTML page."""
assert lib.generate_html()

View file

@ -17,7 +17,6 @@ from modules.archive.api import archive_bp
from modules.docs.api import docs_bp
from modules.inventory import inventory_bp
from modules.map.api import map_bp
from modules.otp.api import otp_bp
from modules.videos.api import videos_bp
from modules.zim.api import zim_bp
from wrolpi import flags, schema, dates
@ -55,7 +54,6 @@ api_app.blueprint(docs_bp)
api_app.blueprint(files_bp)
api_app.blueprint(inventory_bp)
api_app.blueprint(map_bp)
api_app.blueprint(otp_bp)
api_app.blueprint(videos_bp)
api_app.blueprint(zim_bp)