(优化) 优化文件读写与加密逻辑
This commit is contained in:
@@ -15,11 +15,18 @@ static int write_file(const std::string & fname, std::vector<char>& buf){
|
|||||||
}
|
}
|
||||||
// 加密数据
|
// 加密数据
|
||||||
size_t keyIndex = 0;
|
size_t keyIndex = 0;
|
||||||
|
if (ENCRYPTION_KEY.length() > 0) {
|
||||||
for (char& c : buf) {
|
for (char& c : buf) {
|
||||||
c ^= ENCRYPTION_KEY[keyIndex];
|
c ^= ENCRYPTION_KEY[keyIndex];
|
||||||
keyIndex = (keyIndex + 1) % ENCRYPTION_KEY.length();
|
keyIndex = (keyIndex + 1) % ENCRYPTION_KEY.length();
|
||||||
fs << (int)((unsigned char)c) << ",";
|
fs << (int)((unsigned char)c) << ",";
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
for (char& c : buf) {
|
||||||
|
fs << (int)((unsigned char)c) << ",";
|
||||||
|
}
|
||||||
|
}
|
||||||
fs.close();
|
fs.close();
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@@ -38,13 +45,6 @@ static int load_file(const std::string & fname, std::vector<char>& buf){
|
|||||||
buf.resize(fsize);
|
buf.resize(fsize);
|
||||||
fs.read(buf.data(), fsize);
|
fs.read(buf.data(), fsize);
|
||||||
fs.close();
|
fs.close();
|
||||||
|
|
||||||
// 解密数据
|
|
||||||
size_t keyIndex = 0;
|
|
||||||
for(char &c : buf) {
|
|
||||||
c ^= ENCRYPTION_KEY[keyIndex];
|
|
||||||
keyIndex = (keyIndex + 1) % ENCRYPTION_KEY.length();
|
|
||||||
}
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -64,20 +64,10 @@ int main(int argc, char** argv){
|
|||||||
// 如果提供了密码,则进行加密操作
|
// 如果提供了密码,则进行加密操作
|
||||||
if (argc == 4) {
|
if (argc == 4) {
|
||||||
ENCRYPTION_KEY = argv[3];
|
ENCRYPTION_KEY = argv[3];
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
ENCRYPTION_KEY = "";
|
||||||
|
}
|
||||||
write_file(argv[2], content);
|
write_file(argv[2], content);
|
||||||
} else {
|
|
||||||
// 否则,直接写入文件
|
|
||||||
std::ofstream fs(argv[2], std::ios::binary | std::ios::out);
|
|
||||||
if(!fs.good())
|
|
||||||
{
|
|
||||||
std::cerr<<argv[2]<<" does not exist"<<std::endl;
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
for(char c : content) {
|
|
||||||
fs << (int)((unsigned char)c) << ",";
|
|
||||||
}
|
|
||||||
fs.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user