ctr_encryption_layer.cpp 1.8 KB

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