2022-04-23 08:59:50 +00:00
|
|
|
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
|
|
|
|
// SPDX-License-Identifier: GPL-2.0-or-later
|
2018-07-28 03:55:23 +00:00
|
|
|
|
2020-08-03 18:14:39 +00:00
|
|
|
#include <algorithm>
|
2018-07-29 23:00:09 +00:00
|
|
|
#include <cstring>
|
2018-07-28 03:55:23 +00:00
|
|
|
#include "core/crypto/ctr_encryption_layer.h"
|
|
|
|
|
2018-07-29 01:39:42 +00:00
|
|
|
namespace Core::Crypto {
|
|
|
|
|
2018-09-15 13:21:06 +00:00
|
|
|
CTREncryptionLayer::CTREncryptionLayer(FileSys::VirtualFile base_, Key128 key_,
|
2021-05-16 05:46:30 +00:00
|
|
|
std::size_t base_offset_)
|
|
|
|
: EncryptionLayer(std::move(base_)), base_offset(base_offset_), cipher(key_, Mode::CTR) {}
|
2018-07-28 03:55:23 +00:00
|
|
|
|
2018-09-15 13:21:06 +00:00
|
|
|
std::size_t CTREncryptionLayer::Read(u8* data, std::size_t length, std::size_t offset) const {
|
2018-07-28 03:55:23 +00:00
|
|
|
if (length == 0)
|
|
|
|
return 0;
|
|
|
|
|
|
|
|
const auto sector_offset = offset & 0xF;
|
|
|
|
if (sector_offset == 0) {
|
|
|
|
UpdateIV(base_offset + offset);
|
|
|
|
std::vector<u8> raw = base->ReadBytes(length, offset);
|
2018-08-16 20:58:49 +00:00
|
|
|
cipher.Transcode(raw.data(), raw.size(), data, Op::Decrypt);
|
2018-08-25 22:59:19 +00:00
|
|
|
return length;
|
2018-07-28 03:55:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// offset does not fall on block boundary (0x10)
|
|
|
|
std::vector<u8> block = base->ReadBytes(0x10, offset - sector_offset);
|
|
|
|
UpdateIV(base_offset + offset - sector_offset);
|
2018-07-29 01:39:42 +00:00
|
|
|
cipher.Transcode(block.data(), block.size(), block.data(), Op::Decrypt);
|
2018-09-15 13:21:06 +00:00
|
|
|
std::size_t read = 0x10 - sector_offset;
|
2018-07-28 03:55:23 +00:00
|
|
|
|
|
|
|
if (length + sector_offset < 0x10) {
|
2018-07-29 23:00:09 +00:00
|
|
|
std::memcpy(data, block.data() + sector_offset, std::min<u64>(length, read));
|
2018-08-16 20:58:49 +00:00
|
|
|
return std::min<u64>(length, read);
|
2018-07-28 03:55:23 +00:00
|
|
|
}
|
2018-07-29 23:00:09 +00:00
|
|
|
std::memcpy(data, block.data() + sector_offset, read);
|
2018-07-28 03:55:23 +00:00
|
|
|
return read + Read(data + read, length - read, offset + read);
|
|
|
|
}
|
|
|
|
|
2020-08-03 18:14:39 +00:00
|
|
|
void CTREncryptionLayer::SetIV(const IVData& iv_) {
|
|
|
|
iv = iv_;
|
2018-07-28 03:55:23 +00:00
|
|
|
}
|
|
|
|
|
2018-09-15 13:21:06 +00:00
|
|
|
void CTREncryptionLayer::UpdateIV(std::size_t offset) const {
|
2018-07-28 03:55:23 +00:00
|
|
|
offset >>= 4;
|
2018-09-15 13:21:06 +00:00
|
|
|
for (std::size_t i = 0; i < 8; ++i) {
|
2018-07-28 03:55:23 +00:00
|
|
|
iv[16 - i - 1] = offset & 0xFF;
|
|
|
|
offset >>= 8;
|
|
|
|
}
|
|
|
|
cipher.SetIV(iv);
|
|
|
|
}
|
2018-07-29 01:39:42 +00:00
|
|
|
} // namespace Core::Crypto
|