#!/usr/bin/env python3 # SPDX-License-Identifier: MIT # Copyright (c) 2026 M Vijith Menon (Vichitran) # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software # and associated documentation files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or # substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING # BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """SecureKeys password algorithm: reference implementation (Python 3, standard library only). Gives the same password as the SecureKeys app for the same passphrase and options. Versions 3.0 and 4.0.2 onwards lowercase the passphrase using the phone's language. If your phone was set to Turkish, Azerbaijani or Lithuanian, add --language=tr, --language=az or --language=lt as the last argument. Versions 4.0 and 4.0.1 ignored the language: leave the option out for their passwords. Usage: python3 securekeys.py "my passphrase" 12 --mixed-case --special --numbers python3 securekeys.py "my passphrase" 12 --mixed-case --language=tr python3 securekeys.py --check golden.tsv # verify against the published test vectors python3 securekeys.py --check golden_locale_tr.tsv --language=tr """ import hashlib import sys import unicodedata UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" LOWER = "abcdefghijklmnopqrstuvwxyz" DIGITS = "1234567890" SYMBOLS = "()-.?[]_~!#$^*-+=|{}" # Phone languages that lowercase differently from every other language. LANGUAGES = ("tr", "az", "lt") DOT_ABOVE = "\u0307" # Lithuanian: these always keep the dot of the "i" under their accent. LITHUANIAN_ACCENTED = {"\u00cc": "i\u0307\u0300", "\u00cd": "i\u0307\u0301", "\u0128": "i\u0307\u0303"} # The app is written for the JVM, where a string is a sequence of UTF-16 code units. Rotation, # lengths and indexes all count those units, so this implementation does too: plain ASCII # passphrases behave exactly as you'd expect, and emoji or other characters outside the Basic # Multilingual Plane count as two units. def to_units(s: str) -> list: data = s.encode("utf-16-le", "surrogatepass") return [int.from_bytes(data[k:k + 2], "little") for k in range(0, len(data), 2)] def from_units(units: list) -> str: return b"".join(u.to_bytes(2, "little") for u in units).decode("utf-16-le", "surrogatepass") def utf8_like_jvm(units: list) -> bytes: """UTF-8 bytes as the JVM encodes them: a lone surrogate (left by a rotation that split an emoji in two) becomes '?'.""" out = bytearray() k = 0 while k < len(units): u = units[k] if 0xD800 <= u <= 0xDBFF and k + 1 < len(units) and 0xDC00 <= units[k + 1] <= 0xDFFF: out += from_units(units[k:k + 2]).encode("utf-8") k += 2 elif 0xD800 <= u <= 0xDFFF: out += b"?" k += 1 else: out += chr(u).encode("utf-8") k += 1 return bytes(out) def rotate(units: list, n: int) -> list: """Move the first n units to the end. If the sequence is shorter than n, first double it (append it to itself) until it is at least n long: 3 units at n = 7 become 12, not 9.""" while len(units) < n: units = units + units return units[n:] + units[:n] def char_at(phrase: list, i: int, mixed_case: bool, special: bool, numbers: bool) -> str: digest = hashlib.md5(utf8_like_jvm(rotate(phrase + to_units(str(i)), i))).hexdigest() seed = int(digest[24:], 16) # last 8 hex digits, as an unsigned number position = i + 1 if numbers and position % 3 == 0: pool = DIGITS elif mixed_case and position % 4 == 0: pool = UPPER elif special and position % 5 == 0: pool = SYMBOLS else: pool = LOWER return pool[seed % len(pool)] def accent_above_follows(s: str, k: int, wanted: str = "") -> bool: """Whether an accent drawn above (or exactly `wanted`) follows s[k] on the same letter.""" for c in s[k + 1:]: if c == wanted: return True combining_class = unicodedata.combining(c) if combining_class in (0, 230): return not wanted and combining_class == 230 return False def lower(s: str, language: str = "") -> str: """Lowercase as the JVM does for a phone set to `language`.""" if language in ("tr", "az"): out, drop_dot = [], False for k, c in enumerate(s): if c == "I": # "I" followed by a combining dot is a dotted capital: it becomes "i", without the dot. drop_dot = accent_above_follows(s, k, DOT_ABOVE) out.append("i" if drop_dot else "\u0131") elif c == "\u0130": out.append("i") elif c == DOT_ABOVE and drop_dot: drop_dot = False else: out.append(c) s = "".join(out) elif language == "lt": out = [] for k, c in enumerate(s): if c in LITHUANIAN_ACCENTED: out.append(LITHUANIAN_ACCENTED[c]) elif c in ("I", "J", "\u012e") and accent_above_follows(s, k): out.append(c.lower() + DOT_ABOVE) else: out.append(c) s = "".join(out) return s.lower() def generate(passphrase: str, length: int, mixed_case: bool, special: bool, numbers: bool, language: str = "") -> str: """The password for a passphrase. Spaces (U+0020 only) are removed, then the phrase is lowercased by the rules of the phone's language ("tr", "az", "lt", or "" for any other).""" if not passphrase or length <= 0: return "" phrase = to_units(lower(passphrase.replace(" ", ""), language)) raw = "".join(char_at(phrase, i, mixed_case, special, numbers) for i in range(length)) return "".join(chr(u) for u in rotate(to_units(raw), ord(raw[0]) % len(raw))) def unescape(s: str) -> str: """The vector files write tab, newline and backslash in passphrases as \\t, \\n and \\\\.""" out, k = [], 0 while k < len(s): if s[k] == "\\" and k + 1 < len(s): out.append({"t": "\t", "n": "\n", "\\": "\\"}[s[k + 1]]) k += 2 else: out.append(s[k]) k += 1 return "".join(out) def check(path: str, language: str = "") -> int: failures = 0 rows = 0 with open(path, encoding="utf-8") as f: for line in f: if not line.strip(): continue phrase, length, mixed, special, numbers, expected = line.rstrip("\r\n").split("\t") got = generate(unescape(phrase), int(length), mixed == "true", special == "true", numbers == "true", language) rows += 1 if got != expected: failures += 1 print(f"MISMATCH {phrase!a} {length} {mixed} {special} {numbers}: {got!a} != {expected!a}") print(f"{rows - failures}/{rows} vectors match") return 1 if failures or rows == 0 else 0 if __name__ == "__main__": args = sys.argv[1:] # A language option must be last. An unlisted language is left in place and refused below. language = "" if args and args[-1] in {"--language=" + code for code in LANGUAGES}: language = args.pop().split("=")[1] if len(args) == 2 and args[0] == "--check": sys.exit(check(args[1], language)) # Options come after the passphrase and length. Anything else is refused, so a mistyped # option can't silently give a different password. # An empty passphrase, a length below 1 or an option where the passphrase belongs is refused # too, rather than printing an empty or unintended password. known = {"--mixed-case", "--special", "--numbers"} options = set(args[2:]) misplaced = args[:1] and (args[0] in known or args[0] == "--language" or args[0].startswith("--language=")) if len(args) < 2 or not options <= known or misplaced or not args[0] or int(args[1]) < 1: print(__doc__) sys.exit(2) print(generate(args[0], int(args[1]), "--mixed-case" in options, "--special" in options, "--numbers" in options, language))