xts_encryption_layer.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2018 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <cstring>
  6. #include "core/crypto/xts_encryption_layer.h"
  7. namespace Core::Crypto {
  8. constexpr u64 XTS_SECTOR_SIZE = 0x4000;
  9. XTSEncryptionLayer::XTSEncryptionLayer(FileSys::VirtualFile base_, Key256 key_)
  10. : EncryptionLayer(std::move(base_)), cipher(key_, Mode::XTS) {}
  11. std::size_t XTSEncryptionLayer::Read(u8* data, std::size_t length, std::size_t offset) const {
  12. if (length == 0)
  13. return 0;
  14. const auto sector_offset = offset & 0x3FFF;
  15. if (sector_offset == 0) {
  16. if (length % XTS_SECTOR_SIZE == 0) {
  17. std::vector<u8> raw = base->ReadBytes(length, offset);
  18. cipher.XTSTranscode(raw.data(), raw.size(), data, offset / XTS_SECTOR_SIZE,
  19. XTS_SECTOR_SIZE, Op::Decrypt);
  20. return raw.size();
  21. }
  22. if (length > XTS_SECTOR_SIZE) {
  23. const auto rem = length % XTS_SECTOR_SIZE;
  24. const auto read = length - rem;
  25. return Read(data, read, offset) + Read(data + read, rem, offset + read);
  26. }
  27. std::vector<u8> buffer = base->ReadBytes(XTS_SECTOR_SIZE, offset);
  28. if (buffer.size() < XTS_SECTOR_SIZE)
  29. buffer.resize(XTS_SECTOR_SIZE);
  30. cipher.XTSTranscode(buffer.data(), buffer.size(), buffer.data(), offset / XTS_SECTOR_SIZE,
  31. XTS_SECTOR_SIZE, Op::Decrypt);
  32. std::memcpy(data, buffer.data(), std::min(buffer.size(), length));
  33. return std::min(buffer.size(), length);
  34. }
  35. // offset does not fall on block boundary (0x4000)
  36. std::vector<u8> block = base->ReadBytes(0x4000, offset - sector_offset);
  37. if (block.size() < XTS_SECTOR_SIZE)
  38. block.resize(XTS_SECTOR_SIZE);
  39. cipher.XTSTranscode(block.data(), block.size(), block.data(),
  40. (offset - sector_offset) / XTS_SECTOR_SIZE, XTS_SECTOR_SIZE, Op::Decrypt);
  41. const std::size_t read = XTS_SECTOR_SIZE - sector_offset;
  42. if (length + sector_offset < XTS_SECTOR_SIZE) {
  43. std::memcpy(data, block.data() + sector_offset, std::min<u64>(length, read));
  44. return std::min<u64>(length, read);
  45. }
  46. std::memcpy(data, block.data() + sector_offset, read);
  47. return read + Read(data + read, length - read, offset + read);
  48. }
  49. } // namespace Core::Crypto