Skip to content

Commit

Permalink
NANDImporter: Only read the AES key once
Browse files Browse the repository at this point in the history
There is no need to constantly reset the key for every file entry.
  • Loading branch information
Starsam80 committed Mar 2, 2022
1 parent 80012ae commit 41a3368
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 8 deletions.
14 changes: 6 additions & 8 deletions Source/Core/DiscIO/NANDImporter.cpp
Expand Up @@ -4,7 +4,6 @@
#include "DiscIO/NANDImporter.h"

#include <algorithm>
#include <array>
#include <cstring>

#include "Common/Crypto/AES.h"
Expand Down Expand Up @@ -35,8 +34,8 @@ void NANDImporter::ImportNANDBin(const std::string& path_to_bin,
if (!FindSuperblock())
return;

ProcessEntry(0, "");
ExportKeys();
ProcessEntry(0, "");
ExtractCertificates();
}

Expand Down Expand Up @@ -165,13 +164,8 @@ void NANDImporter::ProcessEntry(u16 entry_number, const std::string& parent_path

std::vector<u8> NANDImporter::GetEntryData(const NANDFSTEntry& entry)
{
constexpr size_t NAND_AES_KEY_OFFSET = 0x158;
constexpr size_t NAND_FAT_BLOCK_SIZE = 0x4000;

std::array<u8, 16> key{};
std::copy(&m_nand_keys[NAND_AES_KEY_OFFSET], &m_nand_keys[NAND_AES_KEY_OFFSET + key.size()],
key.begin());

u16 sub = entry.sub;
size_t remaining_bytes = entry.size;
std::vector<u8> data{};
Expand All @@ -181,7 +175,7 @@ std::vector<u8> NANDImporter::GetEntryData(const NANDFSTEntry& entry)
{
std::array<u8, 16> iv{};
std::vector<u8> block = Common::AES::Decrypt(
key.data(), iv.data(), &m_nand[NAND_FAT_BLOCK_SIZE * sub], NAND_FAT_BLOCK_SIZE);
m_aes_key.data(), iv.data(), &m_nand[NAND_FAT_BLOCK_SIZE * sub], NAND_FAT_BLOCK_SIZE);

size_t size = std::min(remaining_bytes, block.size());
data.insert(data.end(), block.begin(), block.begin() + size);
Expand Down Expand Up @@ -264,6 +258,10 @@ bool NANDImporter::ExtractCertificates()

void NANDImporter::ExportKeys()
{
constexpr size_t NAND_AES_KEY_OFFSET = 0x158;

std::copy_n(&m_nand_keys[NAND_AES_KEY_OFFSET], m_aes_key.size(), m_aes_key.begin());

const std::string file_path = m_nand_root + "/keys.bin";
File::IOFile file(file_path, "wb");
if (!file.WriteBytes(m_nand_keys.data(), NAND_KEYS_SIZE))
Expand Down
2 changes: 2 additions & 0 deletions Source/Core/DiscIO/NANDImporter.h
Expand Up @@ -3,6 +3,7 @@

#pragma once

#include <array>
#include <functional>
#include <memory>
#include <string>
Expand Down Expand Up @@ -73,6 +74,7 @@ class NANDImporter final
std::string m_nand_root;
std::vector<u8> m_nand;
std::vector<u8> m_nand_keys;
std::array<u8, 16> m_aes_key;
std::unique_ptr<NANDSuperblock> m_superblock;
std::function<void()> m_update_callback;
};
Expand Down

0 comments on commit 41a3368

Please sign in to comment.