1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
|
// Crypto/RarAes.cpp
// Note: you must include MyAes.cpp to project to initialize AES tables
#include "StdAfx.h"
#include "RarAes.h"
#include "Sha1Cls.h"
namespace NCrypto {
namespace NRar29 {
CDecoder::CDecoder():
CAesCbcDecoder(kRarAesKeySize),
_thereIsSalt(false),
_needCalc(true),
_rar350Mode(false)
{
for (unsigned i = 0; i < sizeof(_salt); i++)
_salt[i] = 0;
}
STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size)
{
bool prev = _thereIsSalt;
_thereIsSalt = false;
if (size == 0)
{
if (!_needCalc && prev)
_needCalc = true;
return S_OK;
}
if (size < 8)
return E_INVALIDARG;
_thereIsSalt = true;
bool same = false;
if (_thereIsSalt == prev)
{
same = true;
if (_thereIsSalt)
{
for (unsigned i = 0; i < sizeof(_salt); i++)
if (_salt[i] != data[i])
{
same = false;
break;
}
}
}
for (unsigned i = 0; i < sizeof(_salt); i++)
_salt[i] = data[i];
if (!_needCalc && !same)
_needCalc = true;
return S_OK;
}
static const unsigned kPasswordLen_MAX = 127 * 2;
STDMETHODIMP CDecoder::CryptoSetPassword(const Byte *data, UInt32 size)
{
if (size > kPasswordLen_MAX)
size = kPasswordLen_MAX;
bool same = false;
if (size == _password.Size())
{
same = true;
for (UInt32 i = 0; i < size; i++)
if (data[i] != _password[i])
{
same = false;
break;
}
}
if (!_needCalc && !same)
_needCalc = true;
_password.CopyFrom(data, (size_t)size);
return S_OK;
}
STDMETHODIMP CDecoder::Init()
{
CalcKey();
RINOK(SetKey(_key, kRarAesKeySize));
RINOK(SetInitVector(_iv, AES_BLOCK_SIZE));
return CAesCbcCoder::Init();
}
void CDecoder::CalcKey()
{
if (!_needCalc)
return;
const unsigned kSaltSize = 8;
Byte buf[kPasswordLen_MAX + kSaltSize];
if (_password.Size() != 0)
memcpy(buf, _password, _password.Size());
size_t rawSize = _password.Size();
if (_thereIsSalt)
{
memcpy(buf + rawSize, _salt, kSaltSize);
rawSize += kSaltSize;
}
NSha1::CContext sha;
sha.Init();
Byte digest[NSha1::kDigestSize];
// rar reverts hash for sha.
const UInt32 kNumRounds = (1 << 18);
UInt32 i;
for (i = 0; i < kNumRounds; i++)
{
sha.UpdateRar(buf, rawSize, _rar350Mode);
Byte pswNum[3] = { (Byte)i, (Byte)(i >> 8), (Byte)(i >> 16) };
sha.UpdateRar(pswNum, 3, _rar350Mode);
if (i % (kNumRounds / 16) == 0)
{
NSha1::CContext shaTemp = sha;
shaTemp.Final(digest);
_iv[i / (kNumRounds / 16)] = (Byte)digest[4 * 4 + 3];
}
}
sha.Final(digest);
for (i = 0; i < 4; i++)
for (unsigned j = 0; j < 4; j++)
_key[i * 4 + j] = (digest[i * 4 + 3 - j]);
_needCalc = false;
}
}}
|