惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
博客园 - 三生石上(FineUI控件)
S
Securelist
U
Unit 42
The Cloudflare Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Simon Willison's Weblog
Simon Willison's Weblog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
B
Blog
T
Tenable Blog
The Hacker News
The Hacker News
The Register - Security
The Register - Security
IT之家
IT之家
博客园 - 【当耐特】
Spread Privacy
Spread Privacy
P
Privacy & Cybersecurity Law Blog
博客园_首页
T
Tailwind CSS Blog
人人都是产品经理
人人都是产品经理
C
Cybersecurity and Infrastructure Security Agency CISA
Know Your Adversary
Know Your Adversary
NISL@THU
NISL@THU
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
阮一峰的网络日志
阮一峰的网络日志
T
Tor Project blog
C
CERT Recently Published Vulnerability Notes
Apple Machine Learning Research
Apple Machine Learning Research
Stack Overflow Blog
Stack Overflow Blog
T
Threat Research - Cisco Blogs
T
The Exploit Database - CXSecurity.com
V
Vulnerabilities – Threatpost
A
Arctic Wolf
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
V
V2EX
aimingoo的专栏
aimingoo的专栏
大猫的无限游戏
大猫的无限游戏
Scott Helme
Scott Helme
L
LINUX DO - 热门话题
Cyberwarzone
Cyberwarzone
V
Visual Studio Blog
月光博客
月光博客
爱范儿
爱范儿
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
美团技术团队
G
GRAHAM CLULEY
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
H
Heimdal Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
From C++ to Rust: When Structure Layout Becomes Part of the Algorithm
Lozi · 2026-06-05 · via DEV Community

Have you ever stumbled upon code that works almost like a miracle, entirely because of how the compiler lays out data in memory?

Recently, while I was working on a port of a decryption for executable files (specifically EBOOT.BIN) from the PSP that was originally written in C++, I found a design pattern that brought me different emotions such as "fascination" and "paranoia"...

Today I want to document how a PSP decryption routine relies on contiguous structure layout to treat multiple adjacent fields as a single cryptographic workspace, the challenges of porting this design to Rust, and how I validated the implementation using an integration test with a real EBOOT.BIN file from Lego Batman.

First case: When The Structure Layout Becomes Part of the Algorithm

Let's analyze the original C++ structure I used to map the encrypted executable layout of the PRXType1 format:

struct PRXType1
{
    explicit PRXType1(const u8 *prx)
    {
        memcpy(tag, prx+0xD0, sizeof(tag));
        memcpy(sha1, prx+0xD4, sizeof(sha1));
        memcpy(unused, prx+0xE8, sizeof(unused));
        memcpy(kirkBlock, prx+0x110, 0x40); 
        memcpy(kirkBlock+0x40, prx+0x80, sizeof(kirkBlock)-0x40);
        memcpy(prxHeader, prx, sizeof(prxHeader));
    }

    void decrypt(int key)
    {
        // LOOK AT THIS NOW
        kirk7(sha1+0xC, sha1+0xC, 0xA0, key);
    }

    u8 tag[4];         // 4 bytes
    u8 sha1[0x14];     // 20 bytes (0x14)
    u8 unused[0x28];   // 40 bytes
    u8 kirkBlock[0x90];// 144 bytes
    u8 prxHeader[0x80];// 128 bytes
};

static_assert(sizeof(PRXType1) == 0x150, "inconsistent size of PRX Type 1");

Enter fullscreen mode Exit fullscreen mode

Now u may ask: Where is the trick?

Pay attention to the decrypt fn. It calls the PSP's cryptographic engine (which is kirk7), passing as a source SHA1 + 0xC.

  • The sha1 array is EXACTLY 0x14 (20 bytes) long
  • If we move 0xC (12 bytes) FORWARD, we only have 8 bytes left in that specific array
  • HOWEVER, the third parameter says to process 0xA0 (which is 160 BYTES)

Now that we know that, Why the program didn't crash? Because the fields reside in a single contiguous structure object. (one after another). Although the pointer originates inside the sha1 field, the cryptographic routine processes 160 consecutive bytes. In practice, this means that the operation spans the remaining bytes of sha1, all of unused, and part of kirkBlock. The implementation therefore treats several adjacent fields as a single contiguous cryptographic workspace.

Because the decryption routine depends on a very specific memory layout, changing the declaration order of the fields would alter the 160-byte region processed by kirk7. Such a change would likely corrupt the decrypted data and break the algorithm entirely.

What Does kirk7 Actually Do?

void kirk7(u8* outbuff, const u8* inbuff, size_t size, int keyId)
{
    AES_ctx aesKey;
    u8* key = kirk_4_7_get_key(keyId);

    AES_set_key(&aesKey, key, 128);
    AES_cbc_decrypt(&aesKey, inbuff, outbuff, size);
}

Enter fullscreen mode Exit fullscreen mode

Since the pointer begins at sha1 + 0xC and the requested size is 0xA0 (160 bytes), the operation spans the remaining bytes of sha1, all of unused, and part of kirkBlock.
In other words, the algorithm is not really interested in the sha1 field itself. It is operating on a 160-byte cryptographic workspace whose starting point happens to lie inside sha1.

The Rust Philosophy: Explicit safety without sacrificing performance.

When I decided to port this to Rust, I quickly realized that the original implementation relies on pointer arithmetic spanning multiple adjacent fields. While Rust can express the same behavior through raw pointers and unsafe code, I wanted a solution that made the memory region explicit and remained fully safe. Instead of relying on a pointer that implicitly goes to several fields, I represented the entire workspace as a single byte array and passed the exact range required by the decryption routine.

To solve this, I decided to use a single flat byte array (which is [u8; 0x150) and create read-only views (slices) based on fixed offsets.

Here is my implementation:

pub struct PrxType1 {
    pub data: [u8; 0x150],
}

impl PrxType1 {
    /// Constructs a new PrxType1 from raw file bytes.
    pub fn new(prx: &[u8]) -> Self {
        let mut data = [0u8; 0x150];

        // Reconstruct the layout respecting the original C++ offsets:
        data[0..4].copy_from_slice(&prx[0xD0..0xD4]);         // tag
        data[4..0x18].copy_from_slice(&prx[0xD4..0xE8]);      // sha1 (20 bytes)
        data[0x18..0x40].copy_from_slice(&prx[0xE8..0x110]);  // unused (40 bytes)
        data[0x40..0x80].copy_from_slice(&prx[0x110..0x150]); // kirkBlock part 1 (64 bytes)
        data[0x80..0xD0].copy_from_slice(&prx[0x80..0xD0]);   // kirkBlock part 2
        data[0xD0..0x150].copy_from_slice(&prx[0..0x80]);     // prxHeader (128 bytes)

        Self { data }
    }

    pub fn decrypt(&mut self, key_id: i32) -> Result<(), KirkError> {
        // In C++ the signature was: kirk7(sha1+0xC, sha1+0xC, 0xA0, key);
        // Our 'sha1' starts at offset 4.
        // 4 + 12 (0xC) = 16 (0x10).
        // If we want to decrypt 160 bytes (0xA0): 16 + 160 = 176 (0xB0).

        // Rust allows us to express the exact memory range explicitly and safely:
        kirk7(&mut self.data[0x10..0xB0], key_id)?;

        Ok(())
    }

    // --- Safe Views (Read-only Slices) ---
    pub fn tag(&self) -> &[u8] { &self.data[0..4] }
    pub fn sha1(&self) -> &[u8] { &self.data[4..0x18] }
    pub fn unused(&self) -> &[u8] { &self.data[0x18..0x40] }
    pub fn kirk_block(&self) -> &[u8] { &self.data[0x40..0xD0] }
    pub fn prx_header(&self) -> &[u8] { &self.data[0xD0..0x150] }    

    /// This verifies integrity by recalculating the header hash (it does this in the original decrypt project but I prefer doing it here)
    pub fn is_valid(&self, xorbuf: &[u8]) -> bool {
        let mut hasher = Sha1::new();

        hasher.update(&xorbuf[0..0x14]);
        hasher.update(self.unused());
        hasher.update(self.kirk_block());
        hasher.update(self.prx_header());

        let hash_calculated = hasher.finalize();
        hash_calculated[..] == self.sha1()[..]
    }
}

Enter fullscreen mode Exit fullscreen mode

Why I think this solution is great?

We keep the extreme performance of C++ because we are doing 0 dynamic allocations or array cloning. By passing the range &mut self.data[0x10..0xB0] to kirk7, Rust guarantees via bounds checking that the cryptographic function operates strictly within those 160 bytes. So if we were to miscalculate the offsets, the program would trigger panic rather than silentyly corrupting other memory.

The moment of Truth

To ensure that this implementation was mathematically justified and the offset math was perfect, I wrote an integration test using the actual EBOOT.BIN file from the Lego Batman Game from the PSP.
This test load the specified file, extract the TAG dinamically, looks up to the corresponding hardware key using a key service (allocated into keys_service.rs), it generates the XOR buffer, runs the decryption, and validates via SHA-1 if the resulting bytes match the game's original structure!!!.

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;
    use std::io::Read;

    #[test]
    fn test_lego_batman_type1_valido() {
        // 1. Load the real PSP binary
        let ruta_eboot = "/home/snake/Downloads/lego_batman_game/PSP_GAME/SYSDIR/EBOOT.BIN";
        let mut file = File::open(ruta_eboot).expect("Could not open EBOOT!");

        let mut eboot_data = Vec::new();
        file.read_to_end(&mut eboot_data).unwrap();

        // 2. Map data to our flat structure
        let mut type1 = PrxType1::new(&eboot_data);

        // 3. Extract the crypto Tag (Should evaluate to 0xC0CB167C automatically)
        let tag_bytes: [u8; 4] = type1.tag().try_into().expect("Tag doesn't have 4 bytes");
        let tag = u32::from_le_bytes(tag_bytes); 

        // 4. Fetch the keys for this specific game
        let key_eboot = keys_service::get_tag_info(tag)
            .expect("This game's Tag is missing from the database!");
        let key_id = key_eboot.code as i32;

        let mut xorbuf = [0u8; 144];
        match &key_eboot.key {
            KeyType::U8(key_array) => { xorbuf.copy_from_slice(*key_array); }
            KeyType::U32(key_array) => {
                for (i, &word) in key_array.iter().enumerate() {
                    let start = i * 4;
                    let end = start + 4;
                    xorbuf[start..end].copy_from_slice(&word.to_le_bytes());
                }
            }
        }

        // 5. Decrypt using our safe Rust memory range!
        type1.decrypt(key_id).expect("AES engine failed...");

        // 6. Final validation: Does the calculated hash match the EBOOT offset?
        let es_valido = type1.is_valid(&xorbuf);

        // If this passes, our contiguous memory emulation was an absolute success
        assert!(es_valido, "SHA-1 hash mismatch... Decryption failed!");
    }
}

Enter fullscreen mode Exit fullscreen mode

Result: TEST PASSED (OK)

We managed to replicate the exact behavior of the original PSP implementation without inheriting it's dangerous security risks

Conclusion

I am writing this article in order to prevent myself from forgetting this architectural headache as the project continues to scale...
Mastering memory isn't just about programming retro consoles. It's about understanding how data layout, performance, and correctness interact in every system we build.