Skip to content

Instantly share code, notes, and snippets.

@araij
Last active July 16, 2016 01:07
Show Gist options
  • Save araij/87409365e05ac4951a0f6e94a3573ab7 to your computer and use it in GitHub Desktop.
Save araij/87409365e05ac4951a0f6e94a3573ab7 to your computer and use it in GitHub Desktop.
(Personal note) Code to decrypt CryptProtectData'ed data
//
// Copyright (C) 2016 Arai, Junya
//
// This program reads CryptProtectData'ed hex string from stdin and decrypt it.
// To compile this with mingw32-g++ on Ubuntu 16.04, type
// x86_64-w64-mingw32-g++ --std=c++14 -o CryptUnprotectData.exe CryptUnprotectData.cc -lcrypt32 -mconsole -static
//
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <windows.h>
#include <wincrypt.h>
std::string read_stdin() {
std::string ln, s;
while (std::getline(std::cin, ln))
s.append(ln);
return s;
}
void remove_space(std::string* const s) {
s->erase(std::remove_if(s->begin(), s->end(),
[](auto c) {return std::isspace(c);}),
s->end());
}
std::vector<BYTE> to_bytes(const std::string& hex) {
std::vector<BYTE> bin;
for (size_t i = 0; i < hex.length() / 2; ++i) {
const auto s = hex.substr(i * 2, 2);
size_t p;
const int v = std::stoi(s, &p, 16);
if (p != 2) {
std::cerr << "ERROR: Not valid hexadecimal character: " << s << std::endl;
exit(EXIT_FAILURE);
}
bin.push_back(static_cast<BYTE>(v));
}
return bin;
}
std::string decrypt(const std::vector<BYTE>& bytes) {
DATA_BLOB cipher = { static_cast<DWORD>(bytes.size())
, const_cast<BYTE*>(&bytes[0]) };
DATA_BLOB plain;
if(!CryptUnprotectData(&cipher, 0, 0, 0, 0, 0, &plain)) {
std::cerr << "ERROR: CryptUnprotectData() failed.\n";
exit(EXIT_FAILURE);
}
return std::string(&plain.pbData[0], &plain.pbData[plain.cbData]);
}
int main(int argc, char* /*argv*/[]) {
if (argc != 1)
std::cerr << "WARNING: The arguments are ignored\n";
auto hex = read_stdin();
remove_space(&hex);
if (hex.length() % 2 != 0) {
std::cerr << "ERROR: The length of ciphertext must be even\n";
exit(EXIT_FAILURE);
}
std::cout << decrypt(to_bytes(hex)) << std::endl;
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment