ctr_encryption_layer.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2018 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <cstring>
  5. #include "common/assert.h"
  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. iv(16, 0) {}
  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 std::vector<u8>& iv_) {
  35. const auto length = std::min(iv_.size(), iv.size());
  36. iv.assign(iv_.cbegin(), iv_.cbegin() + length);
  37. }
  38. void CTREncryptionLayer::UpdateIV(std::size_t offset) const {
  39. offset >>= 4;
  40. for (std::size_t i = 0; i < 8; ++i) {
  41. iv[16 - i - 1] = offset & 0xFF;
  42. offset >>= 8;
  43. }
  44. cipher.SetIV(iv);
  45. }
  46. } // namespace Core::Crypto