void EDDSATests::testKeyGeneration() { AsymmetricKeyPair* kp; // Curves to test std::vector<ByteString> curves; // Add x25519 curves.push_back(ByteString("06032b656e")); // Add ed25519 curves.push_back(ByteString("06032b6570")); for (std::vector<ByteString>::iterator c = curves.begin(); c != curves.end(); c++) { // Set domain parameters ECParameters* p = new ECParameters; p->setEC(*c); // Generate key-pair CPPUNIT_ASSERT(eddsa->generateKeyPair(&kp, p)); EDPublicKey* pub = (EDPublicKey*) kp->getPublicKey(); EDPrivateKey* priv = (EDPrivateKey*) kp->getPrivateKey(); CPPUNIT_ASSERT(pub->getEC() == *c); CPPUNIT_ASSERT(priv->getEC() == *c); eddsa->recycleParameters(p); eddsa->recycleKeyPair(kp); } }
void ECDSATests::testKeyGeneration() { AsymmetricKeyPair* kp; // Curves to test std::vector<ByteString> curves; // Add X9.62 prime256v1 curves.push_back(ByteString("06082a8648ce3d030107")); // Add secp384r1 curves.push_back(ByteString("06052b81040022")); for (std::vector<ByteString>::iterator c = curves.begin(); c != curves.end(); c++) { // Set domain parameters ECParameters* p = new ECParameters; p->setEC(*c); // Generate key-pair CPPUNIT_ASSERT(ecdsa->generateKeyPair(&kp, p)); ECPublicKey* pub = (ECPublicKey*) kp->getPublicKey(); ECPrivateKey* priv = (ECPrivateKey*) kp->getPrivateKey(); CPPUNIT_ASSERT(pub->getEC() == *c); CPPUNIT_ASSERT(priv->getEC() == *c); ecdsa->recycleParameters(p); ecdsa->recycleKeyPair(kp); } }
ByteString CPDF_StreamParser::ReadHexString() { if (!PositionIsInBounds()) return ByteString(); std::ostringstream buf; bool bFirst = true; int code = 0; while (PositionIsInBounds()) { int ch = m_pBuf[m_Pos++]; if (ch == '>') break; if (!std::isxdigit(ch)) continue; int val = FXSYS_HexCharToInt(ch); if (bFirst) { code = val * 16; } else { code += val; buf << static_cast<uint8_t>(code); } bFirst = !bFirst; } if (!bFirst) buf << static_cast<char>(code); if (buf.tellp() <= 0) return ByteString(); return ByteString( buf.str().c_str(), std::min(static_cast<size_t>(buf.tellp()), kMaxStringLength)); }
void PrintVerbose(dev_t device) { fs_info info; if (fs_stat_dev(device, &info) != B_OK) { fprintf(stderr, "Could not stat fs: %s\n", strerror(errno)); return; } printf(" Device No.: %ld\n", info.dev); PrintMountPoint(info.dev, true); printf(" Volume Name: \"%s\"\n", info.volume_name); printf(" File System: %s\n", info.fsh_name); printf(" Device: %s\n", info.device_name); printf(" Flags: "); PrintFlag(info.flags, B_FS_HAS_QUERY, "Q", "-"); PrintFlag(info.flags, B_FS_HAS_ATTR, "A", "-"); PrintFlag(info.flags, B_FS_HAS_MIME, "M", "-"); PrintFlag(info.flags, B_FS_IS_SHARED, "S", "-"); PrintFlag(info.flags, B_FS_IS_PERSISTENT, "P", "-"); PrintFlag(info.flags, B_FS_IS_REMOVABLE, "R", "-"); PrintFlag(info.flags, B_FS_IS_READONLY, "-", "W"); printf("\n I/O Size: %10s (%Ld byte)\n", ByteString(info.io_size, 1), info.io_size); printf(" Block Size: %10s (%Ld byte)\n", ByteString(info.block_size, 1), info.block_size); printf(" Total Blocks: %10s (%Ld blocks)\n", ByteString(info.total_blocks, info.block_size), info.total_blocks); printf(" Free Blocks: %10s (%Ld blocks)\n", ByteString(info.free_blocks, info.block_size), info.free_blocks); printf(" Total Nodes: %Ld\n", info.total_nodes); printf(" Free Nodes: %Ld\n", info.free_nodes); printf(" Root Inode: %Ld\n", info.root); }
int luatpt_message_box(lua_State* l) { String title = ByteString(luaL_optstring(l, 1, "Title")).FromUtf8(); String message = ByteString(luaL_optstring(l, 2, "Message")).FromUtf8(); int large = lua_toboolean(l, 3); new InformationMessage(title, message, large); return 0; }
int luatpt_confirm(lua_State *l) { String title = ByteString(luaL_optstring(l, 1, "Title")).FromUtf8(); String message = ByteString(luaL_optstring(l, 2, "Message")).FromUtf8(); String buttonText = ByteString(luaL_optstring(l, 3, "Confirm")).FromUtf8(); bool ret = ConfirmPrompt::Blocking(title, message, buttonText); lua_pushboolean(l, ret ? 1 : 0); return 1; }
ByteString CFX_V8::ToByteString(v8::Local<v8::Value> pValue) { if (pValue.IsEmpty()) return ByteString(); v8::Local<v8::Context> context = m_pIsolate->GetCurrentContext(); v8::MaybeLocal<v8::String> maybe_string = pValue->ToString(context); if (maybe_string.IsEmpty()) return ByteString(); v8::String::Utf8Value s(GetIsolate(), maybe_string.ToLocalChecked()); return ByteString(*s); }
int luatpt_input(lua_State* l) { String prompt, title, result, shadow, text; title = ByteString(luaL_optstring(l, 1, "Title")).FromUtf8(); prompt = ByteString(luaL_optstring(l, 2, "Enter some text:")).FromUtf8(); text = ByteString(luaL_optstring(l, 3, "")).FromUtf8(); shadow = ByteString(luaL_optstring(l, 4, "")).FromUtf8(); result = TextPrompt::Blocking(title, prompt, text, shadow, false); lua_pushstring(l, result.ToUtf8().c_str()); return 1; }
// Return a substring ByteString ByteString::substr(const size_t start, const size_t len /* = SIZE_T_MAX */) const { size_t retLen = std::min(len, byteString.size() - start); if (start >= byteString.size()) { return ByteString(); } else { return ByteString(&byteString[start], retLen); } }
static bool encodeAttributeMap(ByteString& value, const std::map<CK_ATTRIBUTE_TYPE,OSAttribute>& attributes) { for (std::map<CK_ATTRIBUTE_TYPE,OSAttribute>::const_iterator i = attributes.begin(); i != attributes.end(); ++i) { CK_ATTRIBUTE_TYPE attrType = i->first; value += ByteString((unsigned char*) &attrType, sizeof(attrType)); OSAttribute attr = i->second; if (attr.isBooleanAttribute()) { AttributeKind attrKind = akBoolean; value += ByteString((unsigned char*) &attrKind, sizeof(attrKind)); bool val = attr.getBooleanValue(); value += ByteString((unsigned char*) &val, sizeof(val)); } else if (attr.isUnsignedLongAttribute()) { AttributeKind attrKind = akInteger; value += ByteString((unsigned char*) &attrKind, sizeof(attrKind)); unsigned long val = attr.getUnsignedLongValue(); value += ByteString((unsigned char*) &val, sizeof(val)); } else if (attr.isByteStringAttribute()) { AttributeKind attrKind = akBinary; value += ByteString((unsigned char*) &attrKind, sizeof(attrKind)); ByteString val = attr.getByteStringValue(); unsigned long len = val.size(); value += ByteString((unsigned char*) &len, sizeof(len)); value += val; } else if (attr.isMechanismTypeSetAttribute()) { AttributeKind attrKind = akMechSet; value += ByteString((unsigned char*) &attrKind, sizeof(attrKind)); ByteString val; encodeMechanismTypeSet(val, attr.getMechanismTypeSetValue()); unsigned long len = val.size(); value += ByteString((unsigned char*) &len, sizeof(len)); value += val; } else { ERROR_MSG("unsupported attribute kind for attribute map"); return false; } } return true; }
void ECDSATests::testSigningVerifying() { AsymmetricKeyPair* kp; ECParameters *p; // Curves/Hashes to test std::vector<std::pair<ByteString, const char*> > totest; // Add X9.62 prime256v1 totest.push_back(std::make_pair(ByteString("06082a8648ce3d030107"), "sha256")); // Add secp384r1 totest.push_back(std::make_pair(ByteString("06052b81040022"), "sha384")); for (std::vector<std::pair<ByteString, const char*> >::iterator k = totest.begin(); k != totest.end(); k++) { // Get parameters p = new ECParameters; CPPUNIT_ASSERT(p != NULL); p->setEC(k->first); HashAlgorithm *hash; hash = CryptoFactory::i()->getHashAlgorithm(k->second); CPPUNIT_ASSERT(hash != NULL); // Generate key-pair CPPUNIT_ASSERT(ecdsa->generateKeyPair(&kp, p)); // Generate some data to sign ByteString dataToSign; RNG* rng = CryptoFactory::i()->getRNG(); CPPUNIT_ASSERT(rng != NULL); CPPUNIT_ASSERT(rng->generateRandom(dataToSign, 567)); // Sign the data CPPUNIT_ASSERT(hash->hashInit()); CPPUNIT_ASSERT(hash->hashUpdate(dataToSign)); ByteString hResult; CPPUNIT_ASSERT(hash->hashFinal(hResult)); ByteString sig; CPPUNIT_ASSERT(ecdsa->sign(kp->getPrivateKey(), hResult, sig, "ECDSA")); // And verify it CPPUNIT_ASSERT(ecdsa->verify(kp->getPublicKey(), hResult, sig, "ECDSA")); ecdsa->recycleKeyPair(kp); ecdsa->recycleParameters(p); CryptoFactory::i()->recycleHashAlgorithm(hash); } }
void GOSTTests::readTmpFile(ByteString& data) { unsigned char buf[256]; data.wipe(); #ifdef _WIN32 FILE* in = fopen("gost-hashtest-out.tmp", "r"); #else FILE* in = fopen("gost-hashtest-out.tmp", "rb"); #endif CPPUNIT_ASSERT(in != NULL); int read = 0; do { read = fread(buf, 1, 256, in); data += ByteString(buf, read); } while (read > 0); CPPUNIT_ASSERT(read == 0); CPPUNIT_ASSERT(!fclose(in)); }
String luacon_geterror() { luaL_tostring(luacon_ci->l, -1); String err = ByteString(luaL_optstring(luacon_ci->l, -1, "failed to execute")).FromUtf8(); lua_pop(luacon_ci->l, 1); return err; }
int luatpt_getscript(lua_State* l) { int scriptID = luaL_checkinteger(l, 1); const char *filename = luaL_checkstring(l, 2); int runScript = luaL_optint(l, 3, 0); int confirmPrompt = luaL_optint(l, 4, 1); ByteString url = ByteString::Build(SCHEME "starcatcher.us/scripts/main.lua?get=", scriptID); if (confirmPrompt && !ConfirmPrompt::Blocking("Do you want to install script?", url.FromUtf8(), "Install")) return 0; int ret; ByteString scriptData = http::Request::Simple(url, &ret); if (!scriptData.size() || !filename) { return luaL_error(l, "Server did not return data"); } if (ret != 200) { return luaL_error(l, http::StatusText(ret).ToUtf8().c_str()); } if (!strcmp(scriptData.c_str(), "Invalid script ID\r\n")) { return luaL_error(l, "Invalid Script ID"); } FILE *outputfile = fopen(filename, "r"); if (outputfile) { fclose(outputfile); outputfile = NULL; if (!confirmPrompt || ConfirmPrompt::Blocking("File already exists, overwrite?", ByteString(filename).FromUtf8(), "Overwrite")) { outputfile = fopen(filename, "wb"); } else { return 0; } } else { outputfile = fopen(filename, "wb"); } if (!outputfile) { return luaL_error(l, "Unable to write to file"); } fputs(scriptData.c_str(), outputfile); fclose(outputfile); outputfile = NULL; if (runScript) { luaL_dostring(l, ByteString::Build("dofile('", filename, "')").c_str()); } return 0; }
std::string AvailableMemoryStr() { long long avail_in_bytes = AvailableMemory(); if (avail_in_bytes < 0) return std::string(""); else return ByteString(avail_in_bytes, BYTE_DECIMAL); }
String LuaEvents::luacon_geterror(LuaScriptInterface * luacon_ci) { luaL_tostring(luacon_ci->l, -1); String err = ByteString(luaL_optstring(luacon_ci->l, -1, "failed to execute")).FromUtf8(); lua_pop(luacon_ci->l, 1); return err; }
int luatpt_drawtext(lua_State* l) { const char *string; int textx, texty, textred, textgreen, textblue, textalpha; textx = luaL_optint(l, 1, 0); texty = luaL_optint(l, 2, 0); string = luaL_optstring(l, 3, ""); textred = luaL_optint(l, 4, 255); textgreen = luaL_optint(l, 5, 255); textblue = luaL_optint(l, 6, 255); textalpha = luaL_optint(l, 7, 255); if (textx<0 || texty<0 || textx>=WINDOWW || texty>=WINDOWH) return luaL_error(l, "Screen coordinates out of range (%d,%d)", textx, texty); if (textred<0) textred = 0; if (textred>255) textred = 255; if (textgreen<0) textgreen = 0; if (textgreen>255) textgreen = 255; if (textblue<0) textblue = 0; if (textblue>255) textblue = 255; if (textalpha<0) textalpha = 0; if (textalpha>255) textalpha = 255; luacon_g->drawtext(textx, texty, ByteString(string).FromUtf8(), textred, textgreen, textblue, textalpha); return 0; }
void PairList::PrintMemory() const { size_t total = 0; for (Carray::const_iterator cell = cells_.begin(); cell != cells_.end(); ++cell) total += cell->MemSize(); total += ((Frac_.size() * sizeof(Vec3)) + sizeof(Varray)); mprintf("\tTotal Grid memory: %s\n", ByteString(total, BYTE_DECIMAL).c_str()); }
// Ewald::FillErfcTable() void Ewald::FillErfcTable(double cutoffIn, double dxdr) { one_over_Dx_ = 1.0 / erfcTableDx_; unsigned int erfcTableSize = (unsigned int)(dxdr * one_over_Dx_ * cutoffIn * 1.5); Darray erfc_X, erfc_Y; erfc_X.reserve( erfcTableSize ); erfc_Y.reserve( erfcTableSize ); // Save X and Y values so we can calc the spline coefficients double xval = 0.0; for (unsigned int i = 0; i != erfcTableSize; i++) { double yval = erfc_func( xval ); erfc_X.push_back( xval ); erfc_Y.push_back( yval ); xval += erfcTableDx_; } Spline cspline; cspline.CubicSpline_Coeff(erfc_X, erfc_Y); erfc_X.clear(); // Store values in Spline table erfc_table_.reserve( erfcTableSize * 4 ); // Y B C D for (unsigned int i = 0; i != erfcTableSize; i++) { erfc_table_.push_back( erfc_Y[i] ); erfc_table_.push_back( cspline.B_coeff()[i] ); erfc_table_.push_back( cspline.C_coeff()[i] ); erfc_table_.push_back( cspline.D_coeff()[i] ); } // Memory saved Y values plus spline B, C, and D coefficient arrays. mprintf("\tMemory used by Erfc table and splines: %s\n", ByteString(erfc_table_.size() * sizeof(double), BYTE_DECIMAL).c_str()); }
Chunk* load_chunk(std::ifstream& stream, int x, int z) { ByteString bytes; uint32_t metadataOffset = 4 * (x + z * 32); stream.seekg(metadataOffset); bytes = read_bytes_from_stream(stream, 4); uint32_t offset = bytes.read<uint32_t>() >> 8; if(offset == 0) { return NULL; } stream.seekg(4096 * offset); bytes = read_bytes_from_stream(stream, 5); uint32_t bytecount = bytes.read<uint32_t>(); bytes = read_bytes_from_stream(stream, bytecount - 1); // decompress unsigned long uncompressedLength; ByteString uncompressedData(CHUNK_INFLATE_MAX); std::cout << uncompress(uncompressedData.bytes(), &uncompressedLength, bytes.bytes(), bytecount - 1) << std::endl;; //std::cout << uncompressedLength << std::endl; print_byte_array(uncompressedData.bytes(), uncompressedLength); return read_chunk(ByteString(uncompressedData)); }
TEST(cpdf_nametree, GetUnicodeNameWithBOM) { // Set up the root dictionary with a Names array. auto pRootDict = pdfium::MakeUnique<CPDF_Dictionary>(); CPDF_Array* pNames = pRootDict->SetNewFor<CPDF_Array>("Names"); // Add the key "1" (with BOM) and value 100 into the array. std::ostringstream buf; constexpr char kData[] = "\xFE\xFF\x00\x31"; for (size_t i = 0; i < sizeof(kData); ++i) buf.put(kData[i]); pNames->AddNew<CPDF_String>(ByteString(buf), true); pNames->AddNew<CPDF_Number>(100); // Check that the key is as expected. CPDF_NameTree nameTree(pRootDict.get()); WideString storedName; nameTree.LookupValueAndName(0, &storedName); EXPECT_STREQ(L"1", storedName.c_str()); // Check that the correct value object can be obtained by looking up "1". WideString matchName = L"1"; CPDF_Object* pObj = nameTree.LookupValue(matchName); ASSERT_TRUE(pObj->IsNumber()); EXPECT_EQ(100, pObj->AsNumber()->GetInteger()); }
void EDDSATests::testPKCS8() { // Get ed25519 domain parameters ECParameters* p = new ECParameters; p->setEC(ByteString("06032b6570")); // Generate a key-pair AsymmetricKeyPair* kp; CPPUNIT_ASSERT(eddsa->generateKeyPair(&kp, p)); CPPUNIT_ASSERT(kp != NULL); EDPrivateKey* priv = (EDPrivateKey*) kp->getPrivateKey(); CPPUNIT_ASSERT(priv != NULL); // Encode and decode the private key ByteString pkcs8 = priv->PKCS8Encode(); CPPUNIT_ASSERT(pkcs8.size() != 0); EDPrivateKey* dPriv = (EDPrivateKey*) eddsa->newPrivateKey(); CPPUNIT_ASSERT(dPriv != NULL); CPPUNIT_ASSERT(dPriv->PKCS8Decode(pkcs8)); CPPUNIT_ASSERT(priv->getEC() == dPriv->getEC()); CPPUNIT_ASSERT(priv->getK() == dPriv->getK()); eddsa->recycleParameters(p); eddsa->recycleKeyPair(kp); eddsa->recyclePrivateKey(dPriv); }
void ECDSATests::testPKCS8() { // Get prime256v1 domain parameters ECParameters* p = new ECParameters; p->setEC(ByteString("06082a8648ce3d030107")); // Generate a key-pair AsymmetricKeyPair* kp; CPPUNIT_ASSERT(ecdsa->generateKeyPair(&kp, p)); CPPUNIT_ASSERT(kp != NULL); ECPrivateKey* priv = (ECPrivateKey*) kp->getPrivateKey(); CPPUNIT_ASSERT(priv != NULL); // Encode and decode the private key ByteString pkcs8 = priv->PKCS8Encode(); CPPUNIT_ASSERT(pkcs8.size() != 0); ECPrivateKey* dPriv = (ECPrivateKey*) ecdsa->newPrivateKey(); CPPUNIT_ASSERT(dPriv != NULL); CPPUNIT_ASSERT(dPriv->PKCS8Decode(pkcs8)); CPPUNIT_ASSERT(priv->getEC() == dPriv->getEC()); CPPUNIT_ASSERT(priv->getD() == dPriv->getD()); ecdsa->recycleParameters(p); ecdsa->recycleKeyPair(kp); ecdsa->recyclePrivateKey(dPriv); }
static void encodeMechanismTypeSet(ByteString& value, const std::set<CK_MECHANISM_TYPE>& set) { for (std::set<CK_MECHANISM_TYPE>::const_iterator i = set.begin(); i != set.end(); ++i) { CK_MECHANISM_TYPE mechType = *i; value += ByteString((unsigned char *) &mechType, sizeof(mechType)); } }
int luatpt_textwidth(lua_State* l) { int strwidth = 0; const char* string = luaL_optstring(l, 1, ""); strwidth = Graphics::textwidth(ByteString(string).FromUtf8()); lua_pushinteger(l, strwidth); return 1; }
ByteString Field::mutable_value_as_byte_string() const { Internal::check_type(BYTE_STRING, type()); ib_bytestr_t* bs; throw_if_error(ib_field_mutable_value(ib(), ib_ftype_bytestr_mutable_out(&bs) )); return ByteString(bs); }
void HidDevice::sendFeatureReport(uint8_t reportId, const ByteString& data) { ByteString reportBuf = ByteString(1, reportId) + data; int r = hid_send_feature_report(devHandle, reportBuf.data(), reportBuf.size()); if(r<0) { std::string errorString; utf16BufferToUtf8String(errorString, hid_error(devHandle)); throw HidDeviceError(errorString); } }
ByteString VsbDevice::doQuery(uint8_t cmdId, ByteString data) { ByteString cmdBuf(18, 0); cmdBuf[0] = cmdId; std::copy(data.begin(), data.end(), cmdBuf.begin()+2); sendFeatureReport(VSB_REPORTID, cmdBuf); bool dataOk = false; ByteString resp; for(int i = 0; i < NUM_READ_TRIES; ++i) { try { resp = getFeatureReport(VSB_REPORTID); } catch(HidDeviceError err) { if(i < NUM_READ_TRIES-1) continue; throw VsbError(std::string("HID subsystem error: ") + err.what()); } if(resp.size() < 2) continue; //Probably shouldn't ever happen, but let's not crash if it does if(!resp[0]) continue; //This also shouldn't happen... //FIXME: Implement a proper exception class to use here if(resp[0] != cmdId) throw std::runtime_error(boost::str(boost::format("Got the wrong command ID back! (%d)") % (int)resp[1])); if(resp[1] == VSB_RESP_BUSY) { //TODO: Insert a small time delay continue; } else if(resp[1] == VSB_RESP_NULL) throw VsbError("Null response code?"); else if(resp[1] == VSB_RESP_BADCMD) throw VsbError("Device reported bad command ID"); else if(resp[1] == VSB_RESP_BADCS) throw VsbError("Device reported stored configuration is corrupt/invalid"); else if(resp[1] == VSB_RESP_BADIDX) throw VsbError("Device reported bad keyseq page number"); else if(resp[1] == VSB_RESP_ERR) throw VsbError("Device reported general error"); else if(resp[1] == VSB_RESP_OK) { dataOk = true; break; } else throw VsbError("Got invalid response code"); } if(!dataOk) throw VsbError("Device failed to respond in time"); return ByteString(resp, 2); }
void ECDHTests::testDerivation() { AsymmetricKeyPair* kpa; AsymmetricKeyPair* kpb; ECParameters* p; // Curves to test std::vector<ByteString> curves; // Add X9.62 prime256v1 curves.push_back(ByteString("06082a8648ce3d030107")); // Add secp384r1 curves.push_back(ByteString("06052b81040022")); for (std::vector<ByteString>::iterator c = curves.begin(); c != curves.end(); c++) { // Get parameters p = new ECParameters; CPPUNIT_ASSERT(p != NULL); p->setEC(*c); // Generate key-pairs CPPUNIT_ASSERT(ecdh->generateKeyPair(&kpa, p)); CPPUNIT_ASSERT(ecdh->generateKeyPair(&kpb, p)); // Derive secrets SymmetricKey* sa; CPPUNIT_ASSERT(ecdh->deriveKey(&sa, kpb->getPublicKey(), kpa->getPrivateKey())); SymmetricKey* sb; CPPUNIT_ASSERT(ecdh->deriveKey(&sb, kpa->getPublicKey(), kpb->getPrivateKey())); // Must be the same CPPUNIT_ASSERT(sa->getKeyBits() == sb->getKeyBits()); // Clean up ecdh->recycleSymmetricKey(sa); ecdh->recycleSymmetricKey(sb); ecdh->recycleKeyPair(kpa); ecdh->recycleKeyPair(kpb); ecdh->recycleParameters(p); } }
void PrintBlocks(int64 blocks, int64 blockSize, bool showBlocks) { char temp[1024]; if (showBlocks) sprintf(temp, "%Ld", blocks * (blockSize / 1024)); else strcpy(temp, ByteString(blocks, blockSize)); printf("%10s", temp); }