xts_encryption_layer.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 "common/assert.h"
  7. #include "core/crypto/xts_encryption_layer.h"
  8. namespace Core::Crypto {
  9. constexpr u64 XTS_SECTOR_SIZE = 0x4000;
  10. XTSEncryptionLayer::XTSEncryptionLayer(FileSys::VirtualFile base_, Key256 key_)
  11. : EncryptionLayer(std::move(base_)), cipher(key_, Mode::XTS) {}
  12. std::size_t XTSEncryptionLayer::Read(u8* data, std::size_t length, std::size_t offset) const {
  13. if (length == 0)
  14. return 0;
  15. const auto sector_offset = offset & 0x3FFF;
  16. if (sector_offset == 0) {
  17. if (length % XTS_SECTOR_SIZE == 0) {
  18. std::vector<u8> raw = base->ReadBytes(length, offset);
  19. cipher.XTSTranscode(raw.data(), raw.size(), data, offset / XTS_SECTOR_SIZE,
  20. XTS_SECTOR_SIZE, Op::Decrypt);
  21. return raw.size();
  22. }
  23. if (length > XTS_SECTOR_SIZE) {
  24. const auto rem = length % XTS_SECTOR_SIZE;
  25. const auto read = length - rem;
  26. return Read(data, read, offset) + Read(data + read, rem, offset + read);
  27. }
  28. std::vector<u8> buffer = base->ReadBytes(XTS_SECTOR_SIZE, offset);
  29. if (buffer.size() < XTS_SECTOR_SIZE)
  30. buffer.resize(XTS_SECTOR_SIZE);
  31. cipher.XTSTranscode(buffer.data(), buffer.size(), buffer.data(), offset / XTS_SECTOR_SIZE,
  32. XTS_SECTOR_SIZE, Op::Decrypt);
  33. std::memcpy(data, buffer.data(), std::min(buffer.size(), length));
  34. return std::min(buffer.size(), length);
  35. }
  36. // offset does not fall on block boundary (0x4000)
  37. std::vector<u8> block = base->ReadBytes(0x4000, offset - sector_offset);
  38. if (block.size() < XTS_SECTOR_SIZE)
  39. block.resize(XTS_SECTOR_SIZE);
  40. cipher.XTSTranscode(block.data(), block.size(), block.data(),
  41. (offset - sector_offset) / XTS_SECTOR_SIZE, XTS_SECTOR_SIZE, Op::Decrypt);
  42. const std::size_t read = XTS_SECTOR_SIZE - sector_offset;
  43. if (length + sector_offset < XTS_SECTOR_SIZE) {
  44. std::memcpy(data, block.data() + sector_offset, std::min<u64>(length, read));
  45. return std::min<u64>(length, read);
  46. }
  47. std::memcpy(data, block.data() + sector_offset, read);
  48. return read + Read(data + read, length - read, offset + read);
  49. }
  50. } // namespace Core::Crypto