ctr_encryption_layer.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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/ctr_encryption_layer.h"
  8. namespace Core::Crypto {
  9. CTREncryptionLayer::CTREncryptionLayer(FileSys::VirtualFile base_, Key128 key_,
  10. std::size_t base_offset_)
  11. : EncryptionLayer(std::move(base_)), base_offset(base_offset_), cipher(key_, Mode::CTR) {}
  12. std::size_t CTREncryptionLayer::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 & 0xF;
  16. if (sector_offset == 0) {
  17. UpdateIV(base_offset + offset);
  18. std::vector<u8> raw = base->ReadBytes(length, offset);
  19. cipher.Transcode(raw.data(), raw.size(), data, Op::Decrypt);
  20. return length;
  21. }
  22. // offset does not fall on block boundary (0x10)
  23. std::vector<u8> block = base->ReadBytes(0x10, offset - sector_offset);
  24. UpdateIV(base_offset + offset - sector_offset);
  25. cipher.Transcode(block.data(), block.size(), block.data(), Op::Decrypt);
  26. std::size_t read = 0x10 - sector_offset;
  27. if (length + sector_offset < 0x10) {
  28. std::memcpy(data, block.data() + sector_offset, std::min<u64>(length, read));
  29. return std::min<u64>(length, read);
  30. }
  31. std::memcpy(data, block.data() + sector_offset, read);
  32. return read + Read(data + read, length - read, offset + read);
  33. }
  34. void CTREncryptionLayer::SetIV(const IVData& iv_) {
  35. iv = iv_;
  36. }
  37. void CTREncryptionLayer::UpdateIV(std::size_t offset) const {
  38. offset >>= 4;
  39. for (std::size_t i = 0; i < 8; ++i) {
  40. iv[16 - i - 1] = offset & 0xFF;
  41. offset >>= 8;
  42. }
  43. cipher.SetIV(iv);
  44. }
  45. } // namespace Core::Crypto