Skip to Content
PAPAMO / DOCS

Decrypt a message

Turn your recovery words into the archive key and open message envelopes in your own code, with Node.js and Python examples.

The API and webhooks give you sealed messages. This page shows how to open them on your own system. You need the 12 recovery words from your recovery kit, or the 32-character key.

Tell the two kinds of message apart

Each message's sender field says how it was sealed:

senderbody holdsOpen it with
papamo:encrypted:v1A pSMS envelopeThe archive key, as below
papamo:openpgp:v1An ASCII-armored OpenPGP message (-----BEGIN PGP MESSAGE-----)Your own PGP key and app. The archive key can't open it.

Skip any message that doesn't say papamo:encrypted:v1 before you try the archive key.

From recovery words to the archive key

The 12 words are a standard BIP39 English phrase. There's no password step or key derivation function:

  1. Decode the words with the BIP39 English word list into 16 bytes (the phrase's entropy). pSMS ignores extra spaces and capital letters.
  2. Write those 16 bytes as 32 lowercase hex characters, for example 9d19cc308626be55b4a3f398f567b5fb. This is the 32-character key.
  3. Use the 32 characters of that hex string, as ASCII bytes, as the AES-256 key. Don't decode the hex back into 16 bytes: the key is the text itself.

If you already have the 32-character key, skip to step 3.

Open an envelope

A papamo:encrypted:v1 body is AES-256-GCM:

base64( 12-byte nonce ‖ ciphertext ‖ 16-byte tag )

There's no associated data. The decrypted plaintext is UTF-8 JSON:

{"sender": "+15550100", "body": "Your code is 482913"}

Replies you sent also have "direction": "out", with the other person as sender. Contact cards and queued replies use the same envelope. Messages copied by pSMS for Mac can carry more fields, such as attachments, thread and reply_to; ignore the ones you don't need.

If decryption fails, the key is wrong or the envelope was changed. GCM checks both, so a message that opens is one sealed with your key.

Node.js

Uses Node's built-in crypto and @scure/bip39 (npm install @scure/bip39).

psms-decrypt.mjs
import { createDecipheriv } from "node:crypto";
import { mnemonicToEntropy } from "@scure/bip39";
import { wordlist } from "@scure/bip39/wordlists/english.js";

// Turns the 12 recovery words (or the 32-character key) into the AES-256-GCM key.
export function archiveKey(backup) {
  const value = backup.trim();
  if (value.length === 32 && !/\s/.test(value)) return Buffer.from(value, "ascii");
  const phrase = value.toLowerCase().split(/\s+/).join(" ");
  const entropy = mnemonicToEntropy(phrase, wordlist);
  if (entropy.length !== 16) throw new Error("Expected 12 recovery words.");
  const hex = Buffer.from(entropy).toString("hex"); // 32 lowercase hex characters
  return Buffer.from(hex, "ascii"); // these 32 characters are the key bytes
}

// Opens a papamo:encrypted:v1 envelope. Returns {sender, body} (and "direction": "out" for replies).
export function openEnvelope(key, envelope) {
  const bytes = Buffer.from(envelope, "base64");
  if (bytes.length <= 28) throw new Error("Not a pSMS envelope.");
  const decipher = createDecipheriv("aes-256-gcm", key, bytes.subarray(0, 12));
  decipher.setAuthTag(bytes.subarray(-16));
  const clear = Buffer.concat([decipher.update(bytes.subarray(12, -16)), decipher.final()]);
  return JSON.parse(clear.toString("utf8"));
}

// Finds a one-time code: the domain-bound "@site #code" last line if there is one,
// else the first 4–8 digit number in a text that talks about a code or login.
const CODE_WORDS = /\b(code|otp|passcode|pin|verification|verify|one[- ]?time|password|2fa|mfa|log ?in|sign[- ]?in|authenticat\w*|security|confirm\w*)\b/i;
export function findCode(body) {
  const last = body.trimEnd().split(/\r?\n/).pop();
  const bound = /^@([a-z\d.-]+) #(\d{4,8})$/i.exec(last);
  if (bound) return bound[2];
  if (!CODE_WORDS.test(body)) return null; // "Meet at 1530" isn't a code
  return /(?<!\d)\d{4,8}(?!\d)/.exec(body)?.[0] ?? null;
}

Fetch a message from a self-hosted archive and open it:

import { archiveKey, openEnvelope, findCode } from "./psms-decrypt.mjs";

const key = archiveKey(process.env.PSMS_RECOVERY_WORDS);
const message = await fetch(`${process.env.PSMS_API}/messages/${messageId}`, {
  headers: { authorization: `Bearer ${process.env.PSMS_TOKEN}` },
}).then((r) => r.json());

if (message.sender === "papamo:encrypted:v1") {
  const { sender, body } = openEnvelope(key, message.body);
  console.log(sender, findCode(body));
}

findCode is a starting point. A text that mentions a code and also holds another number, such as an amount, can fool it; a code tagged @site #code on the last line can't.

For a whole webhook handler, see Webhooks.

Python

Uses cryptography and mnemonic (pip install cryptography mnemonic).

psms_decrypt.py
import base64, json, re
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from mnemonic import Mnemonic

def archive_key(backup: str) -> bytes:
    """Turns the 12 recovery words (or the 32-character key) into the AES-256-GCM key."""
    value = backup.strip()
    if len(value) == 32 and not any(c.isspace() for c in value):
        return value.encode("ascii")
    phrase = " ".join(value.lower().split())
    entropy = Mnemonic("english").to_entropy(phrase)
    if len(entropy) != 16:
        raise ValueError("Expected 12 recovery words.")
    return bytes(entropy).hex().encode("ascii")  # these 32 characters are the key bytes

def open_envelope(key: bytes, envelope: str) -> dict:
    """Opens a papamo:encrypted:v1 envelope. Returns {"sender", "body"}."""
    data = base64.b64decode(envelope)
    if len(data) <= 28:
        raise ValueError("Not a pSMS envelope.")
    clear = AESGCM(key).decrypt(data[:12], data[12:], None)
    return json.loads(clear)

CODE_WORDS = re.compile(
    r"\b(code|otp|passcode|pin|verification|verify|one[- ]?time|password|2fa|mfa"
    r"|log ?in|sign[- ]?in|authenticat\w*|security|confirm\w*)\b", re.I)

def find_code(body: str):
    """The domain-bound "@site #code" last line if there is one, else the first
    4–8 digit number in a text that talks about a code or login."""
    last = body.rstrip().splitlines()[-1] if body.strip() else ""
    bound = re.fullmatch(r"@([a-z\d.-]+) #(\d{4,8})", last, re.I)
    if bound:
        return bound.group(2)
    if not CODE_WORDS.search(body):
        return None  # "Meet at 1530" isn't a code
    found = re.search(r"(?<!\d)\d{4,8}(?!\d)", body)
    return found.group(0) if found else None

Fetch a message from a self-hosted archive and open it:

import json, os, urllib.request
from psms_decrypt import archive_key, open_envelope, find_code

key = archive_key(os.environ["PSMS_RECOVERY_WORDS"])
request = urllib.request.Request(
    f"{os.environ['PSMS_API']}/messages/{message_id}",
    headers={"Authorization": f"Bearer {os.environ['PSMS_TOKEN']}"},
)
message = json.load(urllib.request.urlopen(request))
if message["sender"] == "papamo:encrypted:v1":
    text = open_envelope(key, message["body"])
    print(text["sender"], find_code(text["body"]))

papamo.dev has no request for a single message. List the newest with GET /messages?limit=20 and pick the one with the right id.

Check your code

This test phrase is public, so never use it for a real archive. With the words abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about:

  • The 32-character key is 00000000000000000000000000000000.

  • This envelope:

    BwcHBwcHBwcHBwcHsMhvw5IdEUuvrvBcnXzh1DitLYe+Frmoz9/2yo+E1SbXplRcqR5Cxo4EQ2LegnM+47PajnMzCnA/YVU+PHVOqKyAIA==

    opens to {"sender":"+15550100","body":"Your code is 482913"}.

Keep the key safe

Code that holds the recovery words can read every message in the archive, past and future. Keep them in a secret store rather than in source code, and run decryption only on systems you control. See Encryption and access.