A tool for deriving PKG packet encryption keys for ps4 written in c++
| 1 | // SPDX-FileCopyrightText: Copyright 2024 shadPS4 Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #pragma once |
| 5 | |
| 6 | #include <span> |
| 7 | #include <cryptopp/aes.h> |
| 8 | #include <cryptopp/filters.h> |
| 9 | #include <cryptopp/modes.h> |
| 10 | #include <cryptopp/oaep.h> |
| 11 | #include <cryptopp/osrng.h> |
| 12 | #include <cryptopp/rsa.h> |
| 13 | #include <cryptopp/sha.h> |
| 14 | |
| 15 | #include "common/shadpkg_types.h" |
| 16 | #include "keys.h" |
| 17 | |
| 18 | class Crypto { |
| 19 | public: |
| 20 | CryptoPP::RSA::PrivateKey key_pkg_derived_key3_keyset_init(); |
| 21 | CryptoPP::RSA::PrivateKey FakeKeyset_keyset_init(); |
| 22 | CryptoPP::RSA::PrivateKey DebugRifKeyset_init(); |
| 23 | |
| 24 | void RSA2048Decrypt(std::span<CryptoPP::byte, 32> dk3, |
| 25 | std::span<const CryptoPP::byte, 256> ciphertext, |
| 26 | bool is_dk3); // RSAES_PKCS1v15_ |
| 27 | void ivKeyHASH256(std::span<const CryptoPP::byte, 64> cipher_input, |
| 28 | std::span<CryptoPP::byte, 32> ivkey_result); |
| 29 | void aesCbcCfb128Decrypt(std::span<const CryptoPP::byte, 32> ivkey, |
| 30 | std::span<const CryptoPP::byte, 256> ciphertext, |
| 31 | std::span<CryptoPP::byte, 256> decrypted); |
| 32 | void aesCbcCfb128DecryptEntry(std::span<const CryptoPP::byte, 32> ivkey, |
| 33 | std::span<CryptoPP::byte> ciphertext, |
| 34 | std::span<CryptoPP::byte> decrypted); |
| 35 | void decryptEFSM(std::span<CryptoPP::byte, 16> trophyKey, |
| 36 | std::span<CryptoPP::byte, 16> NPcommID, std::span<CryptoPP::byte, 16> efsmIv, |
| 37 | std::span<CryptoPP::byte> ciphertext, std::span<CryptoPP::byte> decrypted); |
| 38 | void PfsGenCryptoKey(std::span<const CryptoPP::byte, 32> ekpfs, |
| 39 | std::span<const CryptoPP::byte, 16> seed, |
| 40 | std::span<CryptoPP::byte, 16> dataKey, |
| 41 | std::span<CryptoPP::byte, 16> tweakKey); |
| 42 | void decryptPFS(std::span<const CryptoPP::byte, 16> dataKey, |
| 43 | std::span<const CryptoPP::byte, 16> tweakKey, std::span<const u8> src_image, |
| 44 | std::span<CryptoPP::byte> dst_image, u64 sector); |
| 45 | |
| 46 | void xtsXorBlock(CryptoPP::byte* x, const CryptoPP::byte* a, const CryptoPP::byte* b) { |
| 47 | for (int i = 0; i < 16; i++) { |
| 48 | x[i] = a[i] ^ b[i]; |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | void xtsMult(std::span<CryptoPP::byte, 16> encryptedTweak) { |
| 53 | int feedback = 0; |
| 54 | for (int k = 0; k < encryptedTweak.size(); k++) { |
| 55 | const auto tmp = (encryptedTweak[k] >> 7) & 1; |
| 56 | encryptedTweak[k] = ((encryptedTweak[k] << 1) + feedback) & 0xFF; |
| 57 | feedback = tmp; |
| 58 | } |
| 59 | if (feedback != 0) { |
| 60 | encryptedTweak[0] ^= 0x87; |
| 61 | } |
| 62 | } |
| 63 | }; |
| 64 |