xref: /aosp_15_r20/external/lzma/CPP/7zip/Crypto/Rar5Aes.h (revision f6dc9357d832569d4d1f5d24eacdb3935a1ae8e6)
1 // Crypto/Rar5Aes.h
2 
3 #ifndef ZIP7_INC_CRYPTO_RAR5_AES_H
4 #define ZIP7_INC_CRYPTO_RAR5_AES_H
5 
6 #include "../../../C/Sha256.h"
7 
8 #include "../../Common/MyBuffer.h"
9 
10 #include "MyAes.h"
11 
12 namespace NCrypto {
13 namespace NRar5 {
14 
15 const unsigned kSaltSize = 16;
16 const unsigned kPswCheckSize32 = 2;
17 const unsigned kAesKeySize = 32;
18 
19 namespace NCryptoFlags
20 {
21   const unsigned kPswCheck = 1 << 0;
22   const unsigned kUseMAC   = 1 << 1;
23 }
24 
25 struct CKeyBase
26 {
27 protected:
28   UInt32 _key32[kAesKeySize / 4];
29   UInt32 _hashKey32[SHA256_NUM_DIGEST_WORDS];
30   UInt32 _check_Calced32[kPswCheckSize32];
31 
WipeCKeyBase32   void Wipe()
33   {
34     memset(this, 0, sizeof(*this));
35   }
36 
CopyCalcedKeysFromCKeyBase37   void CopyCalcedKeysFrom(const CKeyBase &k)
38   {
39     *this = k;
40   }
41 };
42 
43 struct CKey: public CKeyBase
44 {
45   CByteBuffer _password;
46   bool _needCalc;
47   unsigned _numIterationsLog;
48   Byte _salt[kSaltSize];
49 
IsKeyEqualToCKey50   bool IsKeyEqualTo(const CKey &key)
51   {
52     return _numIterationsLog == key._numIterationsLog
53         && memcmp(_salt, key._salt, sizeof(_salt)) == 0
54         && _password == key._password;
55   }
56 
57   CKey();
58   ~CKey();
59 
60   void Wipe();
61 
62 #ifdef Z7_CPP_IS_SUPPORTED_default
63   // CKey(const CKey &) = default;
64   CKey& operator =(const CKey &) = default;
65 #endif
66 };
67 
68 
69 class CDecoder Z7_final:
70   public CAesCbcDecoder,
71   public CKey
72 {
73   UInt32 _check32[kPswCheckSize32];
74   bool _canCheck;
75   UInt64 Flags;
76 
IsThereCheck()77   bool IsThereCheck() const { return (Flags & NCryptoFlags::kPswCheck) != 0; }
78 public:
79   Byte _iv[AES_BLOCK_SIZE];
80 
81   CDecoder();
82 
83   Z7_COM7F_IMP(Init())
84 
85   void SetPassword(const Byte *data, size_t size);
86   HRESULT SetDecoderProps(const Byte *data, unsigned size, bool includeIV, bool isService);
87 
88   bool CalcKey_and_CheckPassword();
89 
UseMAC()90   bool UseMAC() const { return (Flags & NCryptoFlags::kUseMAC) != 0; }
91   UInt32 Hmac_Convert_Crc32(UInt32 crc) const;
92   void Hmac_Convert_32Bytes(Byte *data) const;
93 };
94 
95 }}
96 
97 #endif
98