SPropRecord* parseSPropParameterSets(char const* sPropParameterSetsStr,
                                     // result parameter:
                                     unsigned& numSPropRecords) {
  // Make a copy of the input string, so we can replace the commas with '\0's:
  char* inStr = strDup(sPropParameterSetsStr);
  if (inStr == NULL) {
    numSPropRecords = 0;
    return NULL;
  }

  // Count the number of commas (and thus the number of parameter sets):
  numSPropRecords = 1;
  char* s;
  for (s = inStr; *s != '\0'; ++s) {
    if (*s == ',') {
      ++numSPropRecords;
      *s = '\0';
    }
  }
  
  // Allocate and fill in the result array:
  SPropRecord* resultArray = new SPropRecord[numSPropRecords];
  s = inStr;
  for (unsigned i = 0; i < numSPropRecords; ++i) {
    resultArray[i].sPropBytes = base64Decode(s, resultArray[i].sPropLength);
    s += strlen(s) + 1;
  }

  delete[] inStr;
  return resultArray;
}
Beispiel #2
0
void problem20(void){
	string *ciphers;
	string keystream;
	int numCiphers;
	int i;
	char *line;
	FILE *fp;
	numCiphers=0;

	fp = fopen(FILE20, "r");
	for(i=0; !feof(fp); ) if(fgetc(fp)=='\n') i++;
	fclose(fp);
	numCiphers=++i;

	ciphers=malloc(sizeof(string)*(numCiphers));

	fp=fopen(FILE20, "r");

	line=malloc(sizeof(char)*(161));
	for(i=0; i<numCiphers; i++){
		fscanf(fp, "%s", line);
		ciphers[i]=base64Decode(newString(line,0));
	}
	fclose(fp);

	keystream=breakFixedNonceCTRAsRepeatedXOR(ciphers, numCiphers);
	keystream=modifyKey(keystream, ciphers, numCiphers);
}
Beispiel #3
0
void Page::userStyleSheetLocationChanged()
{
    // FIXME: Eventually we will move to a model of just being handed the sheet
    // text instead of loading the URL ourselves.
    KURL url = m_settings->userStyleSheetLocation();
    if (url.isLocalFile())
        m_userStyleSheetPath = url.fileSystemPath();
    else
        m_userStyleSheetPath = String();

    m_didLoadUserStyleSheet = false;
    m_userStyleSheet = String();
    m_userStyleSheetModificationTime = 0;
    
    // Data URLs with base64-encoded UTF-8 style sheets are common. We can process them
    // synchronously and avoid using a loader. 
    if (url.protocolIs("data") && url.string().startsWith("data:text/css;charset=utf-8;base64,")) {
        m_didLoadUserStyleSheet = true;
        
        const unsigned prefixLength = 35;
        Vector<char> encodedData(url.string().length() - prefixLength);
        for (unsigned i = prefixLength; i < url.string().length(); ++i)
            encodedData[i - prefixLength] = static_cast<char>(url.string()[i]);

        Vector<char> styleSheetAsUTF8;
        if (base64Decode(encodedData, styleSheetAsUTF8))
            m_userStyleSheet = String::fromUTF8(styleSheetAsUTF8.data(), styleSheetAsUTF8.size());
    }
    
    for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext()) {
        if (frame->document())
            frame->document()->clearPageUserSheet();
    }
}
Beispiel #4
0
Status
JsonBox::decrypt(DataChunk &result, DataSlice key)
{
    DataChunk nonce;
    ABC_CHECK(nonceOk());
    ABC_CHECK(base16Decode(nonce, this->nonce()));

    DataChunk cyphertext;
    ABC_CHECK(cyphertextOk());
    ABC_CHECK(base64Decode(cyphertext, this->cyphertext()));

    switch (type())
    {
    case AES256_CBC_AIRBITZ:
    {
        ABC_CHECK_OLD(ABC_CryptoDecryptAES256Package(result,
                      cyphertext, key, nonce,
                      &error));
        return Status();
    }

    default:
        return ABC_ERROR(ABC_CC_DecryptError, "Unknown encryption type");
    }
}
void MyResourceLoader::loadData(const String& data)
{
    LOGD("Loading data (%s) ...", data.latin1().data());
    ResourceHandleClient* client = m_handle->client();
    int index = data.find(',');
    if (index == -1) {
        client->cannotShowURL(m_handle);
        return;
    }

    String mediaType = data.substring(0, index);
    String base64 = data.substring(index + 1);

    bool decode = mediaType.endsWith(";base64", false);
    if (decode)
        mediaType = mediaType.left(mediaType.length() - 7); // 7 for base64;

    if (mediaType.isEmpty())
        mediaType = "text/plain;charset=US-ASCII";

    String mimeType = extractMIMETypeFromMediaType(mediaType);
    String charset = extractCharsetFromMediaType(mediaType);

    ResourceResponse response;
    response.setMimeType(mimeType);

    if (decode) {
        base64 = decodeURLEscapeSequences(base64);
        response.setTextEncodingName(charset);
        client->didReceiveResponse(m_handle, response);

        // FIXME: This is annoying. WebCore's Base64 decoder chokes on spaces.
        // That is correct with strict decoding but html authors (particularly
        // the acid3 authors) put spaces in the data which should be ignored.
        // Remove them here before sending to the decoder.
        Vector<char> in;
        CString str = base64.latin1();
        const char* chars = str.data();
        unsigned i = 0;
        while (i < str.length()) {
            char c = chars[i];
            // Don't send spaces or control characters.
            if (c != ' ' && c != '\n' && c != '\t' && c != '\b'
                    && c != '\f' && c != '\r')
                in.append(chars[i]);
            i++;
        }
        Vector<char> out;
        if (base64Decode(in, out) && out.size() > 0)
            client->didReceiveData(m_handle, out.data(), out.size(), 0);
    } else {
        base64 = decodeURLEscapeSequences(base64, TextEncoding(charset));
        response.setTextEncodingName("UTF-16");
        client->didReceiveResponse(m_handle, response);
        if (base64.length() > 0)
            client->didReceiveData(m_handle, (const char*)base64.characters(),
                    base64.length() * sizeof(UChar), 0);
    }
    client->didFinishLoading(m_handle, 0);
}
JSValue JSDOMWindow::atob(ExecState* exec, const ArgList& args)
{
    if (args.size() < 1)
        return throwError(exec, SyntaxError, "Not enough arguments");

    JSValue v = args.at(0);
    if (v.isNull())
        return jsEmptyString(exec);

    UString s = v.toString(exec);
    if (!s.is8Bit()) {
        setDOMException(exec, INVALID_CHARACTER_ERR);
        return jsUndefined();
    }

    Vector<char> in(s.size());
    for (int i = 0; i < s.size(); ++i)
        in[i] = static_cast<char>(s.data()[i]);
    Vector<char> out;

    if (!base64Decode(in, out))
        return throwError(exec, GeneralError, "Cannot decode base64");

    return jsString(exec, String(out.data(), out.size()));
}
Beispiel #7
0
void Page::userStyleSheetLocationChanged()
{
    // FIXME: Eventually we will move to a model of just being handed the sheet
    // text instead of loading the URL ourselves.
    KURL url = m_settings->userStyleSheetLocation();

    m_didLoadUserStyleSheet = false;
    m_userStyleSheet = String();
    m_userStyleSheetModificationTime = 0;

    // Data URLs with base64-encoded UTF-8 style sheets are common. We can process them
    // synchronously and avoid using a loader.
    if (url.protocolIsData() && url.string().startsWith("data:text/css;charset=utf-8;base64,")) {
        m_didLoadUserStyleSheet = true;

        Vector<char> styleSheetAsUTF8;
        if (base64Decode(decodeURLEscapeSequences(url.string().substring(35)), styleSheetAsUTF8, Base64IgnoreWhitespace))
            m_userStyleSheet = String::fromUTF8(styleSheetAsUTF8.data(), styleSheetAsUTF8.size());
    }

    for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext()) {
        if (frame->document())
            frame->document()->styleSheetCollection()->updatePageUserSheet();
    }
}
Beispiel #8
0
void problem18(void){
	/* Implement CTR, the stream-cipher mode.*/
	string cipher=base64Decode(newString("L77na/nrFsKvynd6HzOoG7GHTLXsTVu9qvY/2syLXzhPweyyMTJULu/6/kXX0KSvoOLSFQ==",0));
	string key=newString("YELLOW SUBMARINE",0);
	string nonce=newString(NULL,8);
	string plaintext=AES128CTR(cipher, key, nonce);
	printf("The CTR-mode encrypted cipher \n"); printsint(cipher);printf("\ndecrypts to \n");prints(plaintext);printf("\n");
}
Beispiel #9
0
TEST_F(ConversionsTests, test_base64) {
  std::string unencoded = "HELLO";
  auto encoded = base64Encode(unencoded);
  EXPECT_NE(encoded.size(), 0U);

  auto unencoded2 = base64Decode(encoded);
  EXPECT_EQ(unencoded, unencoded2);
}
Beispiel #10
0
  virtual void SetUp() {
    std::string raw;
    CFDataRef data;

    raw = base64Decode(getCACertificateContent());
    data = CFDataCreate(NULL, (const UInt8*)raw.c_str(), (CFIndex)raw.size());
    cert = SecCertificateCreateWithData(NULL, data);
    CFRelease(data);
  }
Beispiel #11
0
Status parseApplicationAliasData(const std::string& data, std::string& result) {
  std::string decoded_data = base64Decode(data);
  if (decoded_data.empty()) {
    return Status(1, "Failed to base64 decode data");
  }

  CFDataRef resourceData = CFDataCreate(
      nullptr,
      static_cast<const UInt8*>(static_cast<const void*>(decoded_data.c_str())),
      decoded_data.length());
  if (resourceData == nullptr) {
    return Status(1, "Failed to allocate resource data");
  }

  auto alias = (CFDataRef)CFPropertyListCreateWithData(kCFAllocatorDefault,
                                                       resourceData,
                                                       kCFPropertyListImmutable,
                                                       nullptr,
                                                       nullptr);
  CFRelease(resourceData);
  if (alias == nullptr) {
    return Status(1, "Failed to allocate alias data");
  }

  auto bookmark =
      CFURLCreateBookmarkDataFromAliasRecord(kCFAllocatorDefault, alias);
  CFRelease(alias);
  if (bookmark == nullptr) {
    return Status(1, "Alias data is not a bookmark");
  }

  auto url = CFURLCreateByResolvingBookmarkData(
      kCFAllocatorDefault, bookmark, 0, nullptr, nullptr, nullptr, nullptr);
  CFRelease(bookmark);
  if (url == nullptr) {
    return Status(1, "Alias data is not a URL bookmark");
  }

  auto replaced = CFURLCreateStringByReplacingPercentEscapes(
      kCFAllocatorDefault, CFURLGetString(url), CFSTR(""));
  CFRelease(url);
  if (replaced == nullptr) {
    return Status(1, "Failed to replace percent escapes.");
  }

  // Get the URL-formatted path.
  result = stringFromCFString(replaced);
  CFRelease(replaced);
  if (result.empty()) {
    return Status(1, "Return result is zero size");
  }
  if (result.length() > 6 && result.substr(0, 7) == "file://") {
    result = result.substr(7);
  }

  return Status(0, "OK");
}
Beispiel #12
0
// hash-source       = "'" hash-algorithm "-" hash-value "'"
// hash-algorithm    = "sha1" / "sha256" / "sha384" / "sha512"
// hash-value        = 1*( ALPHA / DIGIT / "+" / "/" / "=" )
//
bool CSPSourceList::parseHash(const UChar* begin, const UChar* end, DigestValue& hash, ContentSecurityPolicyHashAlgorithm& hashAlgorithm)
{
    // Any additions or subtractions from this struct should also modify the
    // respective entries in the kAlgorithmMap array in checkDigest().
    static const struct {
        const char* prefix;
        ContentSecurityPolicyHashAlgorithm type;
    } kSupportedPrefixes[] = {
        // FIXME: Drop support for SHA-1. It's not in the spec.
        { "'sha1-", ContentSecurityPolicyHashAlgorithmSha1 },
        { "'sha256-", ContentSecurityPolicyHashAlgorithmSha256 },
        { "'sha384-", ContentSecurityPolicyHashAlgorithmSha384 },
        { "'sha512-", ContentSecurityPolicyHashAlgorithmSha512 },
        { "'sha-256-", ContentSecurityPolicyHashAlgorithmSha256 },
        { "'sha-384-", ContentSecurityPolicyHashAlgorithmSha384 },
        { "'sha-512-", ContentSecurityPolicyHashAlgorithmSha512 }
    };

    String prefix;
    hashAlgorithm = ContentSecurityPolicyHashAlgorithmNone;
    size_t hashLength = end - begin;

    for (const auto& algorithm : kSupportedPrefixes) {
        if (hashLength > strlen(algorithm.prefix) && equalIgnoringCase(algorithm.prefix, begin, strlen(algorithm.prefix))) {
            prefix = algorithm.prefix;
            hashAlgorithm = algorithm.type;
            break;
        }
    }

    if (hashAlgorithm == ContentSecurityPolicyHashAlgorithmNone)
        return true;

    const UChar* position = begin + prefix.length();
    const UChar* hashBegin = position;

    ASSERT(position < end);
    skipWhile<UChar, isBase64EncodedCharacter>(position, end);
    ASSERT(hashBegin <= position);

    // Base64 encodings may end with exactly one or two '=' characters
    if (position < end)
        skipExactly<UChar>(position, position + 1, '=');
    if (position < end)
        skipExactly<UChar>(position, position + 1, '=');

    if (position + 1 != end || *position != '\'' || position == hashBegin)
        return false;

    Vector<char> hashVector;
    // We accept base64url-encoded data here by normalizing it to base64.
    base64Decode(normalizeToBase64(String(hashBegin, position - hashBegin)), hashVector);
    if (hashVector.size() > kMaxDigestSize)
        return false;
    hash.append(reinterpret_cast<uint8_t*>(hashVector.data()), hashVector.size());
    return true;
}
Beispiel #13
0
// hash-source       = "'" hash-algorithm "-" hash-value "'"
// hash-algorithm    = "sha1" / "sha256" / "sha384" / "sha512"
// hash-value        = 1*( ALPHA / DIGIT / "+" / "/" / "=" )
//
bool CSPSourceList::parseHash(const UChar* begin, const UChar* end, DigestValue& hash, ContentSecurityPolicyHashAlgorithm& hashAlgorithm)
{
    // Any additions or subtractions from this struct should also modify the
    // respective entries in the kAlgorithmMap array in checkDigest().
    static const struct {
        const char* prefix;
        ContentSecurityPolicyHashAlgorithm algorithm;
    } kSupportedPrefixes[] = {
        { "'sha1-", ContentSecurityPolicyHashAlgorithmSha1 },
        { "'sha256-", ContentSecurityPolicyHashAlgorithmSha256 },
        { "'sha384-", ContentSecurityPolicyHashAlgorithmSha384 },
        { "'sha512-", ContentSecurityPolicyHashAlgorithmSha512 }
    };

    String prefix;
    hashAlgorithm = ContentSecurityPolicyHashAlgorithmNone;

    // Instead of this sizeof() calculation to get the length of this array,
    // it would be preferable to use WTF_ARRAY_LENGTH for simplicity and to
    // guarantee a compile time calculation. Unfortunately, on some
    // compliers, the call to WTF_ARRAY_LENGTH fails on arrays of anonymous
    // stucts, so, for now, it is necessary to resort to this sizeof
    // calculation.
    for (size_t i = 0; i < (sizeof(kSupportedPrefixes) / sizeof(kSupportedPrefixes[0])); i++) {
        if (equalIgnoringCase(kSupportedPrefixes[i].prefix, begin, strlen(kSupportedPrefixes[i].prefix))) {
            prefix = kSupportedPrefixes[i].prefix;
            hashAlgorithm = kSupportedPrefixes[i].algorithm;
            break;
        }
    }

    if (hashAlgorithm == ContentSecurityPolicyHashAlgorithmNone)
        return true;

    const UChar* position = begin + prefix.length();
    const UChar* hashBegin = position;

    skipWhile<UChar, isBase64EncodedCharacter>(position, end);
    ASSERT(hashBegin <= position);

    // Base64 encodings may end with exactly one or two '=' characters
    skipExactly<UChar>(position, position + 1, '=');
    skipExactly<UChar>(position, position + 1, '=');

    if ((position + 1) != end || *position != '\'' || !(position - hashBegin))
        return false;

    Vector<char> hashVector;
    base64Decode(hashBegin, position - hashBegin, hashVector);
    if (hashVector.size() > kMaxDigestSize)
        return false;
    hash.append(reinterpret_cast<uint8_t*>(hashVector.data()), hashVector.size());
    return true;
}
Beispiel #14
0
void handleDataURL(ResourceHandle* handle)
{
    ASSERT(handle->firstRequest().url().protocolIs("data"));
    String url = handle->firstRequest().url().string();

    int index = url.find(',');
    if (index == -1) {
        handle->client()->cannotShowURL(handle);
        return;
    }

    String mediaType = url.substring(5, index - 5);
    String data = url.substring(index + 1);

    bool base64 = mediaType.endsWith(";base64", false);
    if (base64)
        mediaType = mediaType.left(mediaType.length() - 7);

    if (mediaType.isEmpty())
        mediaType = "text/plain";

    String mimeType = extractMIMETypeFromMediaType(mediaType);
    String charset = extractCharsetFromMediaType(mediaType);

    if (charset.isEmpty())
        charset = "US-ASCII";

    ResourceResponse response;
    response.setMimeType(mimeType);
    response.setTextEncodingName(charset);
    response.setURL(handle->firstRequest().url());

    if (base64) {
        data = decodeURLEscapeSequences(data);
        handle->client()->didReceiveResponse(handle, response);

        Vector<char> out;
        if (base64Decode(data, out, IgnoreWhitespace) && out.size() > 0) {
            response.setExpectedContentLength(out.size());
            handle->client()->didReceiveData(handle, out.data(), out.size(), 0);
        }
    } else {
        TextEncoding encoding(charset);
        data = decodeURLEscapeSequences(data, encoding);
        handle->client()->didReceiveResponse(handle, response);

        CString encodedData = encoding.encode(data.characters(), data.length(), URLEncodedEntitiesForUnencodables);
        response.setExpectedContentLength(encodedData.length());
        if (encodedData.length())
            handle->client()->didReceiveData(handle, encodedData.data(), encodedData.length(), 0);
    }

    handle->client()->didFinishLoading(handle, 0);
}
std::unordered_map<std::string, Reproduce>
stringToReproduceMap(const std::string &str) {
  const auto data = base64Decode(str);
  std::unordered_map<std::string, Reproduce> reproduceMap;
  try {
    deserialize(begin(data), end(data), reproduceMap);
  } catch (const SerializationException &) {
    throw ParseException(0, "Invalid format");
  }

  return reproduceMap;
}
void ForensicReceiveDataEvent::deserialize(PassRefPtr<JSONObject> json){
	RefPtr<JSONObject> guard = json;
	ForensicEvent::deserialize(guard);

	String temp;
	bool result = guard->getString("data", &temp);
	ASSERT(result);
	base64Decode(temp, m_data);

	result = guard->getNumber("encodedDataLength", &m_encodedDataLength);
	ASSERT(result);
}
Beispiel #17
0
Base64Helper::buffer_type Base64Helper::Decode(const char* text, std::size_t size) {
    buffer_type data;
    
    if (size > 0) {        
        auto decodedSize = GetDecodedSize(text, size);
        data.resize(decodedSize);

        base64Decode(data.data(), text, size);
    }
    
    return data;
}
Beispiel #18
0
std::map<std::string, EcKey::Key> const &getKnownPlayers()
{
	if (knownPlayersIni == nullptr)
	{
		knownPlayersIni = new QSettings(PHYSFS_getWriteDir() + QString("/") + "knownPlayers.ini", QSettings::IniFormat);
		QStringList names = knownPlayersIni->allKeys();
		for (int i = 0; i < names.size(); ++i)
		{
			knownPlayers[names[i].toUtf8().constData()] = base64Decode(knownPlayersIni->value(names[i]).toString().toStdString());
		}
	}
	return knownPlayers;
}
Beispiel #19
0
PassRefPtr<ArchiveResource> MHTMLParser::parseNextPart(const MIMEHeader& mimeHeader, const String& endOfPartBoundary, const String& endOfDocumentBoundary, bool& endOfArchiveReached)
{
    ASSERT(endOfPartBoundary.isEmpty() == endOfDocumentBoundary.isEmpty());

    RefPtr<SharedBuffer> content = SharedBuffer::create();
    const bool checkBoundary = !endOfPartBoundary.isEmpty();
    bool endOfPartReached = false;
    String line;
    while (!(line = m_lineReader.nextLine()).isNull()) {
        if (checkBoundary && (line == endOfPartBoundary || line == endOfDocumentBoundary)) {
            endOfArchiveReached = (line == endOfDocumentBoundary);
            endOfPartReached = true;
            break;
        }
        // Note that we use line.utf8() and not line.ascii() as ascii turns special characters (such as tab, line-feed...) into '?'.
        content->append(line.utf8().data(), line.length());
        if (mimeHeader.contentTransferEncoding() == MIMEHeader::QuotedPrintable) {
            // The line reader removes the \r\n, but we need them for the content in this case as the QuotedPrintable decoder expects CR-LF terminated lines.
            content->append("\r\n", 2);
        }
    }
    if (!endOfPartReached && checkBoundary) {
        LOG_ERROR("No bounday found for MHTML part.");
        return 0;
    }

    Vector<char> data;
    switch (mimeHeader.contentTransferEncoding()) {
    case MIMEHeader::Base64:
        if (!base64Decode(content->data(), content->size(), data)) {
            LOG_ERROR("Invalid base64 content for MHTML part.");
            return 0;
        }
        break;
    case MIMEHeader::QuotedPrintable:
        quotedPrintableDecode(content->data(), content->size(), data);
        break;
    case MIMEHeader::SevenBit:
        data.append(content->data(), content->size());
        break;
    default:
        LOG_ERROR("Invalid encoding for MHTML part.");
        return 0;
    }
    RefPtr<SharedBuffer> contentBuffer = SharedBuffer::adoptVector(data);
    // FIXME: the URL in the MIME header could be relative, we should resolve it if it is.
    // The specs mentions 5 ways to resolve a URL: http://tools.ietf.org/html/rfc2557#section-5
    // IE and Firefox (UNMht) seem to generate only absolute URLs.
    KURL location = KURL(KURL(), mimeHeader.contentLocation());
    return ArchiveResource::create(contentBuffer, location, mimeHeader.contentType(), mimeHeader.charset(), String());
}
  virtual void SetUp() {
    std::string raw;
    CFDataRef data;

    raw = base64Decode(getCACertificateContent());
    data =
        CFDataCreate(nullptr, (const UInt8 *)raw.c_str(), (CFIndex)raw.size());
    cert = SecCertificateCreateWithData(nullptr, data);
    cert_der_data = SecCertificateCopyData(cert);
    auto bytes = CFDataGetBytePtr(cert_der_data);
    x_cert = d2i_X509(nullptr, &bytes, CFDataGetLength(cert_der_data));

    CFRelease(data);
  }
Beispiel #21
0
	int32 getDecorationInfo(const std::string& dn, int32& svid,
		int32& conid, std::string& n){

		std::string b64buf = dn.substr(0, 12);

		std::string buf = base64Decode(b64buf); 

		char* p = (char*)buf.data();
		svid = *(int32*)p;
		conid = *(int32*)(p + sizeof(int32));

		n = dn.substr(12);		

		return 0;
	}	
void InspectorLayerTreeAgent::loadSnapshot(ErrorString* errorString, const String& data, String* snapshotId)
{
    Vector<char> snapshotData;
    if (!base64Decode(data, snapshotData)) {
        *errorString = "Invalid base64 encoding";
        return;
    }
    RefPtr<GraphicsContextSnapshot> snapshot = GraphicsContextSnapshot::load(snapshotData.data(), snapshotData.size());
    if (!snapshot) {
        *errorString = "Invalida snapshot format";
        return;
    }
    *snapshotId = String::number(++s_lastSnapshotId);
    bool newEntry = m_snapshotById.add(*snapshotId, snapshot).isNewEntry;
    ASSERT_UNUSED(newEntry, newEntry);
}
Beispiel #23
0
String DOMWindowBase64::atob(const String& encodedString, ExceptionState& exceptionState)
{
    if (encodedString.isNull())
        return String();

    if (!encodedString.containsOnlyLatin1()) {
        exceptionState.throwDOMException(InvalidCharacterError, "The string to be decoded contains characters outside of the Latin1 range.");
        return String();
    }
    Vector<char> out;
    if (!base64Decode(encodedString, out, isHTMLSpace<UChar>, Base64ValidatePadding)) {
        exceptionState.throwDOMException(InvalidCharacterError, "The string to be decoded is not correctly encoded.");
        return String();
    }

    return String(out.data(), out.size());
}
Beispiel #24
0
void
unpackUploadedFile(const char *post, const char *boundary,
		   char **postb, int *postb_l)
{
	static const char message64[] = "Content-Transfer-Encoding: base64";
	const int boundlen = strlen(boundary);
	const int m64len = strlen(message64);
	char *post2;
	char *b1, *b2, *b3, *b4;	/* boundary points */

	*postb = 0;
	*postb_l = 0;
	if (!strstr(post, message64))
		return;

	post2 = cloneString(post);
	b2 = strstr(post2, boundary);
	while (true) {
		b1 = b2 + boundlen;
		if (*b1 != '\r')
			break;
		b1 += 2;
		b1 = strstr(b1, "Content-Transfer");
		b2 = strstr(b1, boundary);
		if (memcmp(b1, message64, m64len))
			continue;
		b1 += m64len - 6;
		strcpy(b1, "8bit\r\n\r\n");
		b1 += 8;
		b1[0] = b1[1] = ' ';
		b3 = b2 - 4;

		b4 = b3;
		int unpack_ret = base64Decode(b1, &b4);
		if (unpack_ret != GOOD_BASE64_DECODE)
			mail64Error(unpack_ret);
		/* Should we *really* keep going at this point? */
		strmove(b4, b3);
		b2 = b4 + 4;
	}

	b1 += strlen(b1);
	*postb = post2;
	*postb_l = b1 - post2;
}				/* unpackUploadedFile */
Beispiel #25
0
TEST_F(PlistTests, test_parse_plist_content_with_blobs) {
  pt::ptree tree;
  fs::path test_root(kTestDataPath);

  auto s = parsePlist((test_root / "test_binary.plist").string(), tree);
  EXPECT_TRUE(s.ok());
  EXPECT_EQ(s.toString(), "OK");
  EXPECT_THROW(tree.get<bool>("foobar"), pt::ptree_bad_path);
  EXPECT_EQ(tree.get<std::string>("SessionItems.Controller"),
            "CustomListItems");
  auto first_element =
      tree.get_child("SessionItems.CustomListItems").begin()->second;
  EXPECT_EQ(first_element.get<std::string>("Name"), "Flux");
  std::string alias = base64Decode(first_element.get<std::string>("Alias"));

  // Verify we parsed the binary blob correctly
  EXPECT_NE(alias.find("Applications/Flux.app"), std::string::npos);
}
bool SubresourceIntegrity::CheckSubresourceIntegrity(const IntegrityMetadataSet& metadataSet, const char* content, size_t size, const KURL& resourceUrl, Document& document, String& errorMessage)
{
    if (!metadataSet.size())
        return true;

    HashAlgorithm strongestAlgorithm = HashAlgorithmSha256;
    for (const IntegrityMetadata& metadata : metadataSet)
        strongestAlgorithm = getPrioritizedHashFunction(metadata.algorithm(), strongestAlgorithm);

    DigestValue digest;
    for (const IntegrityMetadata& metadata : metadataSet) {
        if (metadata.algorithm() != strongestAlgorithm)
            continue;

        digest.clear();
        bool digestSuccess = computeDigest(metadata.algorithm(), content, size, digest);

        if (digestSuccess) {
            Vector<char> hashVector;
            base64Decode(metadata.digest(), hashVector);
            DigestValue convertedHashVector;
            convertedHashVector.append(reinterpret_cast<uint8_t*>(hashVector.data()), hashVector.size());

            if (DigestsEqual(digest, convertedHashVector)) {
                UseCounter::count(document, UseCounter::SRIElementWithMatchingIntegrityAttribute);
                return true;
            }
        }
    }

    digest.clear();
    if (computeDigest(HashAlgorithmSha256, content, size, digest)) {
        // This message exposes the digest of the resource to the console.
        // Because this is only to the console, that's okay for now, but we
        // need to be very careful not to expose this in exceptions or
        // JavaScript, otherwise it risks exposing information about the
        // resource cross-origin.
        errorMessage = "Failed to find a valid digest in the 'integrity' attribute for resource '" + resourceUrl.elidedString() + "' with computed SHA-256 integrity '" + digestToString(digest) + "'. The resource has been blocked.";
    } else {
        errorMessage = "There was an error computing an integrity value for resource '" + resourceUrl.elidedString() + "'. The resource has been blocked.";
    }
    UseCounter::count(document, UseCounter::SRIElementWithNonMatchingIntegrityAttribute);
    return false;
}
Beispiel #27
0
void InspectorLayerTreeAgent::loadSnapshot(ErrorString* errorString, const RefPtr<JSONArray>& tiles, String* snapshotId)
{
    if (!tiles->length()) {
        *errorString = "Invalid argument, no tiles provided";
        return;
    }
    Vector<RefPtr<PictureSnapshot::TilePictureStream> > decodedTiles;
    decodedTiles.grow(tiles->length());
    for (size_t i = 0; i < tiles->length(); ++i) {
        RefPtr<JSONObject> item;
        if (!tiles->get(i)->asObject(&item)) {
            *errorString = "Invalid argument, array item is not an object";
            return;
        }
        double x = 0, y = 0;
        String picture;
        if (!item->getNumber("x", &x) || !item->getNumber("y", &y)
            || !item->getString("picture", &picture)) {
            *errorString = "Invalid argument, missing required field";
            return;
        }
        decodedTiles[i] = adoptRef(new PictureSnapshot::TilePictureStream());
        decodedTiles[i]->layerOffset.set(x, y);
        if (!base64Decode(picture, decodedTiles[i]->data)) {
            *errorString = "Invalid base64 encoding";
            return;
        }
    }
    RefPtr<PictureSnapshot> snapshot = PictureSnapshot::load(decodedTiles);
    if (!snapshot) {
        *errorString = "Invalid snapshot format";
        return;
    }
    if (snapshot->isEmpty()) {
        *errorString = "Empty snapshot";
        return;
    }

    *snapshotId = String::number(++s_lastSnapshotId);
    bool newEntry = m_snapshotById.add(*snapshotId, snapshot).isNewEntry;
    ASSERT_UNUSED(newEntry, newEntry);
}
 Data Coder::decodeData(const std::string& key)
 {
     if (_valueMap.find(key) == _valueMap.end()) {
         return Data::Null;
     }
     
     const char* encodedData = _valueMap.at(key).asString().c_str();
     unsigned char* decodedData = nullptr;
     int decodedDataLen = base64Decode((unsigned char*)encodedData,
                                       (unsigned int)strlen(encodedData),
                                       &decodedData);
     
     if (decodedData) {
         Data data;
         data.fastSet(decodedData, decodedDataLen);
         return data;
     } else {
         return Data::Null;
     }
 }
Beispiel #29
0
static Sprite* createSpriteFromBase64(const char* base64String)
{
    unsigned char* decoded;
    int length = base64Decode((const unsigned char*) base64String, (unsigned int) strlen(base64String), &decoded);
    
    Image *image = new Image();
    bool imageResult = image->initWithImageData(decoded, length);
    CCASSERT(imageResult, "Failed to create image from base64!");
    free(decoded);
    
    Texture2D *texture = new Texture2D();
    texture->initWithImage(image);
    texture->setAliasTexParameters();
    image->release();
    
    Sprite* sprite = Sprite::createWithTexture(texture);
    texture->release();
    
    return sprite;
}
Beispiel #30
0
/// Parse a Login Items Plist Alias data for bin path
Status parseAliasData(const std::string& data, std::string& result) {
  auto decoded = base64Decode(data);
  if (decoded.size() == 0) {
    // Base64 encoded data (from plist parsing) failed to decode.
    return Status(1, "Failed base64 decode");
  }

  auto alias = CFDataCreate(
      kCFAllocatorDefault, (const UInt8*)decoded.c_str(), decoded.size());
  if (alias == nullptr) {
    // Failed to create CFData object.
    return Status(2, "CFData allocation failed");
  }

  auto bookmark =
      CFURLCreateBookmarkDataFromAliasRecord(kCFAllocatorDefault, alias);
  if (bookmark == nullptr) {
    CFRelease(alias);
    return Status(1, "Alias data is not a bookmark");
  }

  auto url = CFURLCreateByResolvingBookmarkData(
      kCFAllocatorDefault, bookmark, 0, nullptr, nullptr, nullptr, nullptr);
  if (url == nullptr) {
    CFRelease(alias);
    CFRelease(bookmark);
    return Status(1, "Alias data is not a URL bookmark");
  }

  // Get the URL-formatted path.
  result = stringFromCFString(CFURLGetString(url));
  if (result.substr(0, 7) == "file://") {
    result = result.substr(7);
  }

  CFRelease(alias);
  CFRelease(bookmark);
  CFRelease(url);
  return Status(0, "OK");
}