From 19ec34511b31e9fb7f5512c53668d9d6ca5bbeda Mon Sep 17 00:00:00 2001 From: Jan Marvin Garbuszus Date: Tue, 18 Jul 2023 08:30:21 +0200 Subject: [PATCH] switch to Rprintf() --- src/cryptography/cybozu/file.hpp | 4 +- src/cryptography/cybozu/minixml.hpp | 8 +- src/cryptography/cybozu/string.hpp | 7 +- src/cryptography/msoc/include/cfb.hpp | 84 ++-- src/cryptography/msoc/include/crypto_util.hpp | 40 +- src/cryptography/msoc/include/decode.hpp | 10 +- src/cryptography/msoc/include/encode.hpp | 10 +- .../msoc/include/make_dataspace.hpp | 6 +- .../msoc/include/standard_encryption.hpp | 24 +- src/cryptography/msoc/include/uint32vec.hpp | 12 +- src/cryptography/msoc/include/util.hpp | 424 +++++++++--------- 11 files changed, 315 insertions(+), 314 deletions(-) diff --git a/src/cryptography/cybozu/file.hpp b/src/cryptography/cybozu/file.hpp index e177a2c60..be5c470e8 100644 --- a/src/cryptography/cybozu/file.hpp +++ b/src/cryptography/cybozu/file.hpp @@ -165,9 +165,9 @@ class File { sync(); close(); } catch (std::exception& e) { - fprintf(stderr, "File:dstr:%s\n", e.what()); + Rprintf("File:dstr:%s\n", e.what()); } catch (...) { - fprintf(stderr, "File:dstr:unknown\n"); + Rprintf("File:dstr:unknown\n"); } } bool isOpen() const CYBOZU_NOEXCEPT { return hdl_ != INVALID_HANDLE_VALUE; } diff --git a/src/cryptography/cybozu/minixml.hpp b/src/cryptography/cybozu/minixml.hpp index e22c8910b..51aee64cd 100644 --- a/src/cryptography/cybozu/minixml.hpp +++ b/src/cryptography/cybozu/minixml.hpp @@ -103,7 +103,7 @@ class Attributes { std::string tabstr(level + indentWidth, ' '); const char *tab = tabstr.c_str(); for (Map::const_iterator i = m_.begin(), ie = m_.end(); i != ie; ++i) { - printf("%s%s=%s\n", tab, i->first.c_str(), i->second.c_str()); + Rprintf("%s%s=%s\n", tab, i->first.c_str(), i->second.c_str()); } } void swap(Attributes& attr) CYBOZU_NOEXCEPT @@ -166,10 +166,10 @@ struct Node { { std::string tabstr(level, ' '); const char *tab = tabstr.c_str(); - printf("%s<%s>\n", tab, name.c_str()); + Rprintf("%s<%s>\n", tab, name.c_str()); if (!content.empty()) { - printf("%s[content]\n", tab); - printf("%s%s\n", tab, content.c_str()); + Rprintf("%s[content]\n", tab); + Rprintf("%s%s\n", tab, content.c_str()); } attr.put(level); for (NodeList::const_iterator i = child.begin(), ie = child.end(); i != ie; ++i) { diff --git a/src/cryptography/cybozu/string.hpp b/src/cryptography/cybozu/string.hpp index c393170f5..47b9d4f71 100644 --- a/src/cryptography/cybozu/string.hpp +++ b/src/cryptography/cybozu/string.hpp @@ -12,6 +12,7 @@ #pragma warning(disable : 4702) #endif +#include "openxlsx2.h" #include #include #include @@ -302,11 +303,11 @@ class StringT { */ void dump(const char *msg = 0) const { - if (msg) printf("%s", msg); + if (msg) Rprintf("%s", msg); for (size_t i = 0; i < size(); i++) { - printf("%08x ", str_[i]); + Rprintf("%08x ", str_[i]); } - printf("\n"); + Rprintf("\n"); } /** diff --git a/src/cryptography/msoc/include/cfb.hpp b/src/cryptography/msoc/include/cfb.hpp index 6baafd93f..9c86b75fb 100644 --- a/src/cryptography/msoc/include/cfb.hpp +++ b/src/cryptography/msoc/include/cfb.hpp @@ -90,19 +90,19 @@ inline void putCompact(const T& vec) uint32_t v = vec[j]; if (v == prev + 1 && j != n - 1) { if (isFirst) { - printf(" .."); + Rprintf(" .."); isFirst = false; } } else { if (!isFirst && j > 1) { - printf(" %s", toStr(vec[j - 1]).c_str()); + Rprintf(" %s", toStr(vec[j - 1]).c_str()); } - printf(" %s", toStr(v).c_str()); + Rprintf(" %s", toStr(v).c_str()); isFirst = true; } prev = v; } - putchar('\n'); + Rprintf("\n"); } struct Header { @@ -271,17 +271,17 @@ struct Header { void put() const { if (!isDebug()) return; - printf("version : major = %u, minor = 0x%04x\n", majorVersion, minorVersion); - printf("sectorShift = %u\n", sectorShift); - printf("numDirectorySectors = %u\n", numDirectorySectors); - printf("numFatSectors = %u\n", numFatSectors); - printf("firstDirectorySectorLocation = %u\n", firstDirectorySectorLocation); - printf("transactionSignatureNumber = %u\n", transactionSignatureNumber); - printf("firstMiniFatSectorLocation = %s\n", toStr(firstMiniFatSectorLocation).c_str()); - printf("numMiniFatSectors = %u\n", numMiniFatSectors); - printf("firstDifatSectorLocation = %s\n", toStr(firstDifatSectorLocation).c_str()); - printf("numDifatSectors = %u\n", numDifatSectors); - printf("difat size=%d\n", (int)difat.size()); + Rprintf("version : major = %u, minor = 0x%04x\n", majorVersion, minorVersion); + Rprintf("sectorShift = %u\n", sectorShift); + Rprintf("numDirectorySectors = %u\n", numDirectorySectors); + Rprintf("numFatSectors = %u\n", numFatSectors); + Rprintf("firstDirectorySectorLocation = %u\n", firstDirectorySectorLocation); + Rprintf("transactionSignatureNumber = %u\n", transactionSignatureNumber); + Rprintf("firstMiniFatSectorLocation = %s\n", toStr(firstMiniFatSectorLocation).c_str()); + Rprintf("numMiniFatSectors = %u\n", numMiniFatSectors); + Rprintf("firstDifatSectorLocation = %s\n", toStr(firstDifatSectorLocation).c_str()); + Rprintf("numDifatSectors = %u\n", numDifatSectors); + Rprintf("difat size=%d\n", (int)difat.size()); putCompact(difat); } private: @@ -451,7 +451,7 @@ struct DirectoryEntry { startingSectorLocation = cybozu::Get32bitAsLE(data + 0x74); streamSize = cybozu::Get64bitAsLE(data + 0x78); if (streamSize >= uint64_t(0x100000000ULL)) { - printf("warning too large size=%lld\n", (long long)streamSize); + Rprintf("warning too large size=%lld\n", (long long)streamSize); // clear upper 32bit if version 3 streamSize &= 0xffffffff; } @@ -525,29 +525,29 @@ struct DirectoryEntry { void put() const { if (!isDebug()) return; - printf("directoryEntryName = "); + Rprintf("directoryEntryName = "); #ifdef _WIN32 if (directoryEntryName.empty()) { - printf(""); + Rprintf(""); } else { - printf("%S", &directoryEntryName[0]); + Rprintf("%S", &directoryEntryName[0]); } #else - printf("%s", toHex(reinterpret_cast(&directoryEntryName[0]), directoryEntryNameLength).c_str()); + Rprintf("%s", toHex(reinterpret_cast(&directoryEntryName[0]), directoryEntryNameLength).c_str()); #endif - printf("(%u)\n", directoryEntryNameLength); - printf("objectType = %d(%s)\n", objectType, toStr(objectType).c_str()); - printf("colorFlag = %d(%s)\n", colorFlag, toStr(colorFlag).c_str()); - printf("leftSiblingId = %s, ", toStr(leftSiblingId).c_str()); - printf("rightSiblingId = %s\n", toStr(rightSiblingId).c_str()); - printf("childId = %s\n", toStr(childId).c_str()); - printf("clsid = %s, ", toHex(clsid.c_str(), clsid.size()).c_str()); - printf("stateBits = 0x%08x\n", stateBits); - printf("creation/modified Time = %s / %s\n", creationTime.toString().c_str(), modifiedTime.toString().c_str()); - printf("startingSectorLocation = %s\n", toStr(startingSectorLocation).c_str()); - printf("streamSize = %lld\n", (long long)streamSize); + Rprintf("(%u)\n", directoryEntryNameLength); + Rprintf("objectType = %d(%s)\n", objectType, toStr(objectType).c_str()); + Rprintf("colorFlag = %d(%s)\n", colorFlag, toStr(colorFlag).c_str()); + Rprintf("leftSiblingId = %s, ", toStr(leftSiblingId).c_str()); + Rprintf("rightSiblingId = %s\n", toStr(rightSiblingId).c_str()); + Rprintf("childId = %s\n", toStr(childId).c_str()); + Rprintf("clsid = %s, ", toHex(clsid.c_str(), clsid.size()).c_str()); + Rprintf("stateBits = 0x%08x\n", stateBits); + Rprintf("creation/modified Time = %s / %s\n", creationTime.toString().c_str(), modifiedTime.toString().c_str()); + Rprintf("startingSectorLocation = %s\n", toStr(startingSectorLocation).c_str()); + Rprintf("streamSize = %lld\n", (long long)streamSize); if (content.empty()) { - printf("data=\n"); + Rprintf("data=\n"); } else { if (isDebug(2)) { std::string fileName = cybozu::ToUtf8(directoryEntryName) + ".dump"; @@ -558,18 +558,18 @@ struct DirectoryEntry { saveFile(fileName, content); } if (streamSize <= 256) { - printf("data=\n"); + Rprintf("data=\n"); dump16(content, content.size()); } else { - printf("data=["); + Rprintf("data=["); for (size_t i = 0; i < 5; i++) { - printf("%02x:", (uint8_t)content[i]); + Rprintf("%02x:", (uint8_t)content[i]); } - printf(" ... "); + Rprintf(" ... "); for (size_t i = content.size() - 5; i < content.size(); i++) { - printf("%02x:", (uint8_t)content[i]); + Rprintf("%02x:", (uint8_t)content[i]); } - printf("]\n"); + Rprintf("]\n"); } } } @@ -761,13 +761,13 @@ struct CompoundFile { { if (!isDebug()) return; header.put(); - printf("FatSectors\n"); + Rprintf("FatSectors\n"); fats.put(); - printf("mini FatSectors\n"); + Rprintf("mini FatSectors\n"); miniFats.put(); for (size_t i = 0; i < dirs.size(); i++) { - printf("----------------------------\n"); - printf("DirectoryEntry %lld\n", (long long)i); + Rprintf("----------------------------\n"); + Rprintf("DirectoryEntry %lld\n", (long long)i); dirs[i].put(); } } diff --git a/src/cryptography/msoc/include/crypto_util.hpp b/src/cryptography/msoc/include/crypto_util.hpp index 87642b621..e87bfcd3e 100644 --- a/src/cryptography/msoc/include/crypto_util.hpp +++ b/src/cryptography/msoc/include/crypto_util.hpp @@ -45,7 +45,7 @@ Xbyak::util::Clock clk; struct XXX { ~XXX() { - printf("%.1f Mclk\n", clk.getClock() / double(clk.getCount()) * 1e-6); + Rprintf("%.1f Mclk\n", clk.getClock() / double(clk.getCount()) * 1e-6); } } xxx; #endif @@ -115,13 +115,13 @@ struct CipherParam { } void put() const { - printf("cipherName = %s\n", cipherNameStr.c_str()); - printf("saltSize = %d\n", (int)saltSize); - printf("blockSize = %d\n", (int)blockSize); - printf("keyBits = %d\n", (int)keyBits); - printf("hashName = %s\n", hashNameStr.c_str()); - printf("hashSize = %d\n", hashSize); - printf("saltValue = "); dump(saltValue, false); + Rprintf("cipherName = %s\n", cipherNameStr.c_str()); + Rprintf("saltSize = %d\n", (int)saltSize); + Rprintf("blockSize = %d\n", (int)blockSize); + Rprintf("keyBits = %d\n", (int)keyBits); + Rprintf("hashName = %s\n", hashNameStr.c_str()); + Rprintf("hashSize = %d\n", hashSize); + Rprintf("saltValue = "); dump(saltValue, false); } explicit CipherParam(const cybozu::minixml::Node *node) { @@ -272,23 +272,23 @@ struct EncryptionInfo { void put() const { if (!isDebug(0)) return; - printf("major = %d\n", major); - printf("minor = %d\n", minor); - printf("isStandardEncryption = %d\n", isStandardEncryption); + Rprintf("major = %d\n", major); + Rprintf("minor = %d\n", minor); + Rprintf("isStandardEncryption = %d\n", isStandardEncryption); if (isStandardEncryption) { seHeader.put(); seVerifier.put(); } else { - printf("spinCount = %d\n", spinCount); - puts("keyData"); + Rprintf("spinCount = %d\n", spinCount); + Rprintf("keyData"); keyData.put(); - printf("encryptedHmacKey = "); dump(encryptedHmacKey, false); - printf("encryptedHmacValue = "); dump(encryptedHmacValue, false); - puts("encryptedKey"); + Rprintf("encryptedHmacKey = "); dump(encryptedHmacKey, false); + Rprintf("encryptedHmacValue = "); dump(encryptedHmacValue, false); + Rprintf("encryptedKey"); encryptedKey.put(); - printf("encryptedVerifierHashInput = "); dump(encryptedVerifierHashInput, false); - printf("encryptedVerifierHashValue = "); dump(encryptedVerifierHashValue, false); - printf("encryptedKeyValue = "); dump(encryptedKeyValue, false); + Rprintf("encryptedVerifierHashInput = "); dump(encryptedVerifierHashInput, false); + Rprintf("encryptedVerifierHashValue = "); dump(encryptedVerifierHashValue, false); + Rprintf("encryptedKeyValue = "); dump(encryptedKeyValue, false); } } @@ -311,7 +311,7 @@ struct EncryptionInfo { p += encryptionHeaderSize; dataSize -= encryptionHeaderSize; - printf("dataSize=%u\n", (uint32_t)dataSize); + Rprintf("dataSize=%u\n", (uint32_t)dataSize); seVerifier.analyze(p, dataSize); seVerifier.put(); } diff --git a/src/cryptography/msoc/include/decode.hpp b/src/cryptography/msoc/include/decode.hpp index 28f3aad25..4407e7dbf 100644 --- a/src/cryptography/msoc/include/decode.hpp +++ b/src/cryptography/msoc/include/decode.hpp @@ -104,8 +104,8 @@ inline bool getAgileSecretKey(std::string& secretKey, const EncryptionInfo& info const std::string skey3 = generateKey(encryptedKey, pwHash, ms::blkKey_encryptedKeyValue); secretKey = cipher(encryptedKey.cipherName, info.encryptedKeyValue, skey3, iv, cybozu::crypto::Cipher::Decoding); if (isDebug()) { - printf("salt = "); dump(keyData.saltValue, false); - printf("secretKey = "); dump(secretKey, false); + Rprintf("salt = "); dump(keyData.saltValue, false); + Rprintf("secretKey = "); dump(secretKey, false); } return true; } @@ -117,11 +117,11 @@ inline bool decodeAgile(std::string& decData, const std::string& encryptedPackag if (secretKey.empty()) { if (!getAgileSecretKey(secretKey, info, pass)) return false; if (putSecretKeyInstance()) { - printf("secretKey = "); ms::dump(secretKey, false); + Rprintf("secretKey = "); ms::dump(secretKey, false); } if (!VerifyIntegrity(encryptedPackage, keyData, secretKey, keyData.saltValue, info.encryptedHmacKey, info.encryptedHmacValue)) { - printf("warning : mac err : data may be broken\n"); + Rprintf("warning : mac err : data may be broken\n"); // return false; } } @@ -162,7 +162,7 @@ inline bool decodeStandardEncryption(std::string& dec, const std::string& encryp } } if (isDebug()) { - printf("secretKey = "); dump(secretKey, false); + Rprintf("secretKey = "); dump(secretKey, false); } const char *p = encryptedPackage.data(); diff --git a/src/cryptography/msoc/include/encode.hpp b/src/cryptography/msoc/include/encode.hpp index fbfde9eab..e8211777c 100644 --- a/src/cryptography/msoc/include/encode.hpp +++ b/src/cryptography/msoc/include/encode.hpp @@ -96,7 +96,7 @@ inline void EncContent(std::string& encryptedPackage, const std::string& org, co } /* -これの逆順で暗号化 +ソスソスソスソスフ逆ソスソスソスナ暗搾ソスソスソス fix parameter : c1(blkKey_VerifierHashInput) c2(blkKey_encryptedVerifierHashValue) c3(blkKey_encryptedKeyValue) @@ -107,20 +107,20 @@ output: iv, encryptedVerifierHashValue, encryptedKeyValue -iv(encryptedKey.saltValue)をランダム生成 +iv(encryptedKey.saltValue)ソスソスソスソスソスソスソス_ソスソスソスソスソスソス pwHash = hashPassword(iv, pass, spinCount) skey1 = generateKey(pwHash, c1) skey2 = generateKey(pwHash, c2) -verifierHashInputをランダム生成 +verifierHashInputソスソスソスソスソスソスソス_ソスソスソスソスソスソス encryptedVerifierHashInput = Enc(verifierHashInput, skey1, iv) hashedVerifier = H(verifierHashInput) encryptedVerifierHashValue = Enc(verifierHash, skey2, iv) skey3 = generateKey(pwHash, c3) -secretKeyをランダム生成 +secretKeyソスソスソスソスソスソスソス_ソスソスソスソスソスソス encryptedKeyValue = Enc(secretKey, skey3, iv) */ @@ -150,7 +150,7 @@ inline bool encode_in( std::string& iv = encryptedKey.saltValue; FillRand(iv, encryptedKey.saltSize); #ifdef SAME_KEY - puts("QQQ defined SAME_KEY QQQ"); + Rprintf("QQQ defined SAME_KEY QQQ"); iv = fromHex("F4994F9B2DCD5E0E84BC6386D4523D2C"); #endif const std::string pwHash = hashPassword(encryptedKey.hashName, iv, pass, spinCount); diff --git a/src/cryptography/msoc/include/make_dataspace.hpp b/src/cryptography/msoc/include/make_dataspace.hpp index 0f1b958bb..bacb5c6d5 100644 --- a/src/cryptography/msoc/include/make_dataspace.hpp +++ b/src/cryptography/msoc/include/make_dataspace.hpp @@ -48,13 +48,13 @@ inline void makeDataSpace( /7:Transformation/8:StrongEncryptionTransform/9:Primary(F) <10:B> - /\ + ソス^ソス_ <2:R> <1:R> --------------- <4:B> - /\ + ソス^ソス_ <3:B> <5:B> - \ + ソス_ <7:R> --------------- <6:B> diff --git a/src/cryptography/msoc/include/standard_encryption.hpp b/src/cryptography/msoc/include/standard_encryption.hpp index 4abae7790..d26c66798 100644 --- a/src/cryptography/msoc/include/standard_encryption.hpp +++ b/src/cryptography/msoc/include/standard_encryption.hpp @@ -71,13 +71,13 @@ struct EncryptionHeader { } void put() const { - printf("flags = %08x\n", flags); - printf("sizeExtra = %u\n", sizeExtra); - printf("algId = %08x\n", algId); - printf("algIdHash = %08x\n", algIdHash); - printf("keySize = %u\n", keySize); - printf("providerType = %08x\n", providerType); - printf("cspName = %s\n", cybozu::ToUtf8(cspName).c_str()); + Rprintf("flags = %08x\n", flags); + Rprintf("sizeExtra = %u\n", sizeExtra); + Rprintf("algId = %08x\n", algId); + Rprintf("algIdHash = %08x\n", algIdHash); + Rprintf("keySize = %u\n", keySize); + Rprintf("providerType = %08x\n", providerType); + Rprintf("cspName = %s\n", cybozu::ToUtf8(cspName).c_str()); } }; @@ -134,11 +134,11 @@ struct EncryptionVerifier { } void put() const { - printf("saltSize = %d\n", saltSize); - printf("salt = "); ms::dump(salt); - printf("encryptedVerifier = "); ms::dump(encryptedVerifier); - printf("verifierHashSize = %d\n", verifierHashSize); - printf("encryptedVerifierHash = "); ms::dump(encryptedVerifierHash); + Rprintf("saltSize = %d\n", saltSize); + Rprintf("salt = "); ms::dump(salt); + Rprintf("encryptedVerifier = "); ms::dump(encryptedVerifier); + Rprintf("verifierHashSize = %d\n", verifierHashSize); + Rprintf("encryptedVerifierHash = "); ms::dump(encryptedVerifierHash); } }; diff --git a/src/cryptography/msoc/include/uint32vec.hpp b/src/cryptography/msoc/include/uint32vec.hpp index 0f9171fed..4c32eadf4 100644 --- a/src/cryptography/msoc/include/uint32vec.hpp +++ b/src/cryptography/msoc/include/uint32vec.hpp @@ -55,9 +55,9 @@ struct Uint32VecT<8> { { uint32_t v[8]; memcpy(&v, &x_, sizeof(v)); - if (msg) printf("%s", msg); - printf("%08x:%08x:%08x:%08x", v[3], v[2], v[1], v[0]); - if (msg) putchar('\n'); + if (msg) Rprintf("%s", msg); + Rprintf("%08x:%08x:%08x:%08x", v[3], v[2], v[1], v[0]); + if (msg) Rprintf('\n'); } }; @@ -133,9 +133,9 @@ struct Uint32VecT<4> { { uint32_t v[4]; memcpy(&v, &x_, sizeof(v)); - if (msg) printf("%s", msg); - printf("%08x:%08x:%08x:%08x", v[3], v[2], v[1], v[0]); - if (msg) putchar('\n'); + if (msg) Rprintf("%s", msg); + Rprintf("%08x:%08x:%08x:%08x", v[3], v[2], v[1], v[0]); + if (msg) Rprintf('\n'); } }; diff --git a/src/cryptography/msoc/include/util.hpp b/src/cryptography/msoc/include/util.hpp index 104d6e7b8..8cb9508f0 100644 --- a/src/cryptography/msoc/include/util.hpp +++ b/src/cryptography/msoc/include/util.hpp @@ -1,212 +1,212 @@ -#pragma once -/** - @file - @brief MS Office encryption util - Copyright (C) 2012 Cybozu Labs, Inc., all rights reserved. -*/ -#include -#include -#include -#include -#include -#include -#include - -namespace ms { - -enum Format { - fZip, // not encrypted(maybe) - fCfb, // encrypted(maybe) - fUnknown -}; - -inline int& debugInstance() -{ - static int debug; - return debug; -} - -inline void setDebug(int level) -{ - debugInstance() = level; -} - -inline bool& putSecretKeyInstance() -{ - static bool putSecretKey; - return putSecretKey; -} - -inline bool isDebug(int level = 1) { return debugInstance() > level; } - -inline void dprintf(const char *format, ...) -{ - if (!isDebug()) return; - va_list args; - va_start(args, format); -#ifdef __GNUC__ - /*#pragma GCC diagnostic push*/ - /*#pragma GCC diagnostic ignored "-Wformat-nonliteral"*/ -#endif - vprintf(format, args); -#ifdef __GNUC__ - /*#pragma GCC diagnostic pop*/ -#endif - va_end(args); -} - -template -T getBlockNum(T size, T block) -{ - return (size + block - 1) / block; -} -/* - round up size to multiple of block -*/ -template -T RoundUp(T size, T block) -{ - return getBlockNum(size, block) * block; -} - -inline void dump(const void *p, size_t size, bool putColon = true) -{ - const uint8_t *str = reinterpret_cast(p); - for (size_t i = 0; i < size; i++) { - printf("%02X", (unsigned char)str[i]); - if (putColon) putchar(':'); - } - printf("\n"); -} - -inline void dump(const std::string& str, bool putColon = true) -{ - dump(str.c_str(), str.size(), putColon); -} - -inline void dump16(const std::string& str, size_t size = size_t(-1)) -{ - if (size > str.size()) size = str.size(); - for (size_t i = 0; i < size; i++) { - printf("%02X ", (unsigned char)str[i]); - if ((i % 16) == 15) putchar('\n'); - } - printf("\n"); -} - -inline void saveFile(const std::string& file, const std::string& str) -{ - cybozu::File f(file, std::ios::out); - f.write(str.c_str(), str.size()); -} - -inline std::string fromHex(const std::string& hex, bool skipColon = false) -{ - const size_t n = hex.size(); - if (!skipColon && n & 1) throw cybozu::Exception("ms:fromhex:odd length") << n; - std::string ret; - for (size_t i = 0; i < n; i += 2) { - if (skipColon && hex[i] == ':') { - i++; - if (i == n) break; - } - unsigned char c = cybozu::hextoi(&hex[i], 2); - ret += (char)c; - } - return ret; -} - -inline std::string hex(const std::string& str) -{ - const size_t n = str.size(); - std::string ret; - ret.reserve(n * 2); - for (size_t i = 0; i < n; i++) { - ret += cybozu::itohex(static_cast(str[i])); - } - return ret; -} - -inline bool dumpDiff(const std::string& x, const std::string& y) -{ - printf("dumpDiff %d %d\n", (int)x.size(), (int)y.size()); - int ccc = 0; - for (int i = 0; i < (int)std::min(x.size(), y.size()); i++) { - char c = x[i]; - char d = y[i]; - if (c != d) { - printf("%8d(0x%x) %02x %02x\n", i, i, (uint8_t)c, (uint8_t)d); - ccc++; - if (ccc == 100) break; - } - } - if (ccc == 0) printf("no diff\n"); - return ccc == 0; -} - -inline std::string dec64(const std::string& str) -{ - std::string ret; - cybozu::StringInputStream is(str); - cybozu::StringOutputStream os(ret); - cybozu::DecodeFromBase64(os, is); - return ret; -} - -inline std::string enc64(const std::string& str) -{ - std::string ret; - cybozu::StringInputStream is(str); - cybozu::StringOutputStream os(ret); - cybozu::EncodeToBase64(os, is, 128, cybozu::base64::noEndLine); - return ret; -} - -inline void validate(bool isOK, const char *msg, const char *file, int line) -{ - if (!isOK) { - throw cybozu::Exception("ms:cfb:validate") << msg << file << line; - } -} - -template -void validateEqual(const L& a, const R& b, const char *pa, const char *pb, const char *file, int line) -{ - if (a != b) { - throw cybozu::Exception("ms:cfb:validateEqual") << pa << a << pb << b << file << line; - } -} - -inline std::string toHex(const char *p, size_t size) -{ - std::string ret; - for (size_t i = 0; i < size; i++) { - cybozu::itohex(ret, static_cast(p[i]), false); - } - return ret; -} - -inline Format DetectFormat(const char *data, size_t dataSize) -{ - if (dataSize < 8) throw cybozu::Exception("ms:detectFormat:too small") << dataSize; - if (memcmp(data, "PK\x03\x04", 4) == 0) return fZip; - if (memcmp(data, "\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1", 8) == 0) return fCfb; - throw cybozu::Exception("ms:DetectFormat:unknown format") << hex(std::string(data, 8)); -} - -inline std::string Char16toChar8(const cybozu::String16& w) -{ - std::string s; - for (size_t i = 0; i < w.size(); i++) { - cybozu::Char16 c = w[i]; - s += char(c & 0xff); - s += char(c >> 8); - } - return s; -} - -#define MS_ASSERT(x) ms::validate((x), #x, __FILE__, __LINE__) -#define MS_ASSERT_EQUAL(x, y) ms::validateEqual((x), (y), #x, #y, __FILE__, __LINE__) -#define PUT(x) printf(#x "=%s(%d)\n", ms::hex(x).c_str(), (int)x.size()) - -} // ms +#pragma once +/** + @file + @brief MS Office encryption util + Copyright (C) 2012 Cybozu Labs, Inc., all rights reserved. +*/ +#include +#include +#include +#include +#include +#include +#include + +namespace ms { + +enum Format { + fZip, // not encrypted(maybe) + fCfb, // encrypted(maybe) + fUnknown +}; + +inline int& debugInstance() +{ + static int debug; + return debug; +} + +inline void setDebug(int level) +{ + debugInstance() = level; +} + +inline bool& putSecretKeyInstance() +{ + static bool putSecretKey; + return putSecretKey; +} + +inline bool isDebug(int level = 1) { return debugInstance() > level; } + +inline void dprintf(const char *format, ...) +{ + if (!isDebug()) return; + va_list args; + va_start(args, format); +#ifdef __GNUC__ + /*#pragma GCC diagnostic push*/ + /*#pragma GCC diagnostic ignored "-Wformat-nonliteral"*/ +#endif + vprintf(format, args); +#ifdef __GNUC__ + /*#pragma GCC diagnostic pop*/ +#endif + va_end(args); +} + +template +T getBlockNum(T size, T block) +{ + return (size + block - 1) / block; +} +/* + round up size to multiple of block +*/ +template +T RoundUp(T size, T block) +{ + return getBlockNum(size, block) * block; +} + +inline void dump(const void *p, size_t size, bool putColon = true) +{ + const uint8_t *str = reinterpret_cast(p); + for (size_t i = 0; i < size; i++) { + Rprintf("%02X", (unsigned char)str[i]); + if (putColon) Rprintf(":"); + } + Rprintf("\n"); +} + +inline void dump(const std::string& str, bool putColon = true) +{ + dump(str.c_str(), str.size(), putColon); +} + +inline void dump16(const std::string& str, size_t size = size_t(-1)) +{ + if (size > str.size()) size = str.size(); + for (size_t i = 0; i < size; i++) { + Rprintf("%02X ", (unsigned char)str[i]); + if ((i % 16) == 15) Rprintf("\n"); + } + Rprintf("\n"); +} + +inline void saveFile(const std::string& file, const std::string& str) +{ + cybozu::File f(file, std::ios::out); + f.write(str.c_str(), str.size()); +} + +inline std::string fromHex(const std::string& hex, bool skipColon = false) +{ + const size_t n = hex.size(); + if (!skipColon && n & 1) throw cybozu::Exception("ms:fromhex:odd length") << n; + std::string ret; + for (size_t i = 0; i < n; i += 2) { + if (skipColon && hex[i] == ':') { + i++; + if (i == n) break; + } + unsigned char c = cybozu::hextoi(&hex[i], 2); + ret += (char)c; + } + return ret; +} + +inline std::string hex(const std::string& str) +{ + const size_t n = str.size(); + std::string ret; + ret.reserve(n * 2); + for (size_t i = 0; i < n; i++) { + ret += cybozu::itohex(static_cast(str[i])); + } + return ret; +} + +inline bool dumpDiff(const std::string& x, const std::string& y) +{ + Rprintf("dumpDiff %d %d\n", (int)x.size(), (int)y.size()); + int ccc = 0; + for (int i = 0; i < (int)std::min(x.size(), y.size()); i++) { + char c = x[i]; + char d = y[i]; + if (c != d) { + Rprintf("%8d(0x%x) %02x %02x\n", i, i, (uint8_t)c, (uint8_t)d); + ccc++; + if (ccc == 100) break; + } + } + if (ccc == 0) Rprintf("no diff\n"); + return ccc == 0; +} + +inline std::string dec64(const std::string& str) +{ + std::string ret; + cybozu::StringInputStream is(str); + cybozu::StringOutputStream os(ret); + cybozu::DecodeFromBase64(os, is); + return ret; +} + +inline std::string enc64(const std::string& str) +{ + std::string ret; + cybozu::StringInputStream is(str); + cybozu::StringOutputStream os(ret); + cybozu::EncodeToBase64(os, is, 128, cybozu::base64::noEndLine); + return ret; +} + +inline void validate(bool isOK, const char *msg, const char *file, int line) +{ + if (!isOK) { + throw cybozu::Exception("ms:cfb:validate") << msg << file << line; + } +} + +template +void validateEqual(const L& a, const R& b, const char *pa, const char *pb, const char *file, int line) +{ + if (a != b) { + throw cybozu::Exception("ms:cfb:validateEqual") << pa << a << pb << b << file << line; + } +} + +inline std::string toHex(const char *p, size_t size) +{ + std::string ret; + for (size_t i = 0; i < size; i++) { + cybozu::itohex(ret, static_cast(p[i]), false); + } + return ret; +} + +inline Format DetectFormat(const char *data, size_t dataSize) +{ + if (dataSize < 8) throw cybozu::Exception("ms:detectFormat:too small") << dataSize; + if (memcmp(data, "PK\x03\x04", 4) == 0) return fZip; + if (memcmp(data, "\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1", 8) == 0) return fCfb; + throw cybozu::Exception("ms:DetectFormat:unknown format") << hex(std::string(data, 8)); +} + +inline std::string Char16toChar8(const cybozu::String16& w) +{ + std::string s; + for (size_t i = 0; i < w.size(); i++) { + cybozu::Char16 c = w[i]; + s += char(c & 0xff); + s += char(c >> 8); + } + return s; +} + +#define MS_ASSERT(x) ms::validate((x), #x, __FILE__, __LINE__) +#define MS_ASSERT_EQUAL(x, y) ms::validateEqual((x), (y), #x, #y, __FILE__, __LINE__) +#define PUT(x) Rprintf(#x "=%s(%d)\n", ms::hex(x).c_str(), (int)x.size()) + +} // ms