"""Offline Android SharedPreferences XML & digest verifier (Ch 82: tutorial-sharedpreferences)."""
from __future__ import annotations
import hashlib
import json
import sys
import tempfile
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Any
VERSION = "CPython 3.12.14 offline Android storage/HTTP/WebView verifier (Android SDK/emulator absent)"
class XmlSharedPreferences:
"""Minimal SharedPreferences XML persistence matching Android /shared_prefs/<name>.xml."""
def __init__(self, xml_path: Path, mode: str = "MODE_PRIVATE"):
self.xml_path = xml_path
self.mode = mode
self._data: dict[str, Any] = {}
if self.xml_path.exists():
self._load()
def _load(self) -> None:
tree = ET.parse(self.xml_path)
root = tree.getroot()
self._data.clear()
for child in root:
key = child.attrib["name"]
if child.tag == "string":
self._data[key] = child.text or ""
elif child.tag == "int":
self._data[key] = int(child.attrib["value"])
elif child.tag == "long":
self._data[key] = int(child.attrib["value"])
elif child.tag == "float":
self._data[key] = float(child.attrib["value"])
elif child.tag == "boolean":
self._data[key] = child.attrib["value"].lower() == "true"
def _save(self) -> bool:
self.xml_path.parent.mkdir(parents=True, exist_ok=True)
root = ET.Element("map")
for key, val in sorted(self._data.items()):
if isinstance(val, bool):
ET.SubElement(root, "boolean", name=key, value="true" if val else "false")
elif isinstance(val, int):
ET.SubElement(root, "int", name=key, value=str(val))
elif isinstance(val, float):
ET.SubElement(root, "float", name=key, value=str(val))
else:
el = ET.SubElement(root, "string", name=key)
el.text = str(val)
ET.ElementTree(root).write(self.xml_path, encoding="utf-8", xml_declaration=True)
return True
def put(self, key: str, value: Any) -> None:
self._data[key] = value
def commit(self) -> bool:
return self._save()
def get(self, key: str, default: Any = "") -> Any:
return self._data.get(key, default)
def remove(self, key: str) -> None:
self._data.pop(key, None)
def clear(self) -> None:
self._data.clear()
def contains(self, key: str) -> bool:
return key in self._data
def get_all(self) -> dict[str, Any]:
return dict(self._data)
def md5_hex(text: str) -> str:
return hashlib.md5(text.encode("utf-8")).hexdigest()
def md5_x100(text: str) -> str:
cur = text
for _ in range(100):
cur = md5_hex(cur)
return cur
def main() -> None:
cases = []
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
sp_file = base / "data/data/com.example.spdemo/shared_prefs/mysp.xml"
# Case 1: Basic SharedPreferences save & restart reload from XML
sp = XmlSharedPreferences(sp_file)
sp.put("username", "alice")
sp.put("passwd", "s3cr3t")
committed = sp.commit()
reloaded = XmlSharedPreferences(sp_file)
xml_text = sp_file.read_text(encoding="utf-8")
actual1 = {
"committed": committed,
"username": reloaded.get("username", ""),
"passwd": reloaded.get("passwd", ""),
"has_map_root": "<map>" in xml_text and "</map>" in xml_text,
}
expected1 = {
"committed": True,
"username": "alice",
"passwd": "s3cr3t",
"has_map_root": True,
}
cases.append({
"name": "sharedpreferences_xml_persistence",
"summary": "Verify SharedPreferences XML write, commit(), and process-restart reload.",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: Cross-app access control: MODE_PRIVATE isolation vs deprecated MODE_WORLD_READABLE
def access_other_app_sp(target_mode: str, api_level: int) -> str:
if target_mode == "MODE_PRIVATE":
return "EACCES_DENIED"
if api_level >= 24:
return "SecurityException_MODE_WORLD_READABLE_FORBIDDEN"
return "LEGACY_READ_ALLOWED"
actual2 = {
"private_api21": access_other_app_sp("MODE_PRIVATE", 21),
"world_readable_api21": access_other_app_sp("MODE_WORLD_READABLE", 21),
"world_readable_api24_plus": access_other_app_sp("MODE_WORLD_READABLE", 24),
}
expected2 = {
"private_api21": "EACCES_DENIED",
"world_readable_api21": "LEGACY_READ_ALLOWED",
"world_readable_api24_plus": "SecurityException_MODE_WORLD_READABLE_FORBIDDEN",
}
cases.append({
"name": "cross_app_sp_isolation_policy",
"summary": "Verify MODE_PRIVATE sandbox isolation and Android 7.0 (API 24+) SecurityException on MODE_WORLD_READABLE.",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: MD5 single vs 100-round digest properties + modern salted PBKDF2 comparison
d1 = md5_hex("呵呵")
d1_16 = d1[8:24]
d100 = md5_x100("呵呵")
pbkdf2_a = hashlib.pbkdf2_hmac("sha256", b"password123", b"salt-A", 100_000).hex()
pbkdf2_b = hashlib.pbkdf2_hmac("sha256", b"password123", b"salt-B", 100_000).hex()
actual3 = {
"md5_len": len(d1),
"md5_16_len": len(d1_16),
"md5_16_is_middle": d1[8:24] == d1_16,
"md5_deterministic": d1 == md5_hex("呵呵"),
"md5_x100_len": len(d100),
"md5_x100_differs": d100 != d1,
"salted_pbkdf2_unique_per_salt": pbkdf2_a != pbkdf2_b and len(pbkdf2_a) == 64,
}
expected3 = {
"md5_len": 32,
"md5_16_len": 16,
"md5_16_is_middle": True,
"md5_deterministic": True,
"md5_x100_len": 32,
"md5_x100_differs": True,
"salted_pbkdf2_unique_per_salt": True,
}
cases.append({
"name": "md5_digest_and_modern_salted_kdf",
"summary": "Verify 32-char/16-char MD5 properties, 100-round MD5 iteration, and salted PBKDF2-HMAC-SHA256 uniqueness.",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: SPUtils typed put/get/contains/remove/getAll/clear
util_sp = XmlSharedPreferences(base / "data/data/com.example.spdemo/shared_prefs/my_sp.xml")
util_sp.put("auto_login", True)
util_sp.put("retry_count", 3)
util_sp.put("font_scale", 1.25)
util_sp.put("theme", "dark")
util_sp.commit()
reloaded2 = XmlSharedPreferences(util_sp.xml_path)
snapshot_before_remove = reloaded2.get_all()
has_theme_before = reloaded2.contains("theme")
reloaded2.remove("theme")
reloaded2.commit()
has_theme_after = XmlSharedPreferences(util_sp.xml_path).contains("theme")
reloaded2.clear()
reloaded2.commit()
after_clear = XmlSharedPreferences(util_sp.xml_path).get_all()
actual4 = {
"typed_snapshot": snapshot_before_remove,
"has_theme_before": has_theme_before,
"has_theme_after": has_theme_after,
"after_clear": after_clear,
}
expected4 = {
"typed_snapshot": {
"auto_login": True,
"font_scale": 1.25,
"retry_count": 3,
"theme": "dark",
},
"has_theme_before": True,
"has_theme_after": False,
"after_clear": {},
}
cases.append({
"name": "sputils_typed_crud_and_clear",
"summary": "Verify SPUtils multi-type persistence (bool/int/float/str), contains(), remove(), getAll(), and clear().",
"expected": expected4,
"actual": actual4,
"passed": actual4 == expected4,
})
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
sys.exit(main())
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/android-tutorial-sharedpreferences-lab/explore-tutorial-sharedpreferences.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-sharedpreferences.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1945.zip