Exemplo n.º 1
0
uint_fast8_t tmdLoadHeader(tmd_data *data, wchar_t *path) { //validate and load tmd header
	File fil;
	size_t offset, size;
	tmd_data data_tmp;
	tmd_content_chunk *content_chunk_tmp;
	uint_fast16_t content_count;
	uint8_t hash[SHA_256_SIZE];
	
	if (!FileOpen(&fil, path, 0) || (
		(FileRead2(&fil, &data_tmp.sig_type, sizeof(data_tmp.sig_type)) != sizeof(data_tmp.sig_type) ||
		(offset = tmdHeaderOffset(data_tmp.sig_type)) == 0 ||
		!FileSeek(&fil, offset) ||
		FileRead2(&fil, &data_tmp.header, sizeof(data_tmp.header) + sizeof(data_tmp.content_info)) != sizeof(data_tmp.header) + sizeof(data_tmp.content_info)) &&
		(FileClose(&fil) || 1)
	)) return 0;
	sha(hash, &data_tmp.content_info, sizeof(data_tmp.content_info), SHA_256_MODE);
	if (memcmp(hash, data_tmp.header.content_info_hash, sizeof(hash))) return FileClose(&fil) && 0;
	size = (content_count = __builtin_bswap16(data_tmp.header.content_count)) * sizeof(tmd_content_chunk);
	content_chunk_tmp = __builtin_alloca(size);
	if (FileRead2(&fil, content_chunk_tmp, size) != size) return FileClose(&fil) && 0;
	FileClose(&fil);
	for (uint_fast16_t info_index = 0, chunk_index = 0, chunk_count; chunk_index < content_count; info_index++, chunk_index += chunk_count) {
		if (info_index >= sizeof(data_tmp.content_info)/sizeof(tmd_content_info) ||
			(chunk_count = __builtin_bswap16(data_tmp.content_info[info_index].content_command_count)) == 0
		) return 0;
		sha(hash, &content_chunk_tmp[chunk_index], chunk_count * sizeof(tmd_content_chunk), SHA_256_MODE);
		if (memcmp(hash, data_tmp.content_info[chunk_index].content_chunk_hash, sizeof(hash))) return 0;
	}
	*data = data_tmp;
	return 1;
}
Exemplo n.º 2
0
 std::c14::enable_if_t<is_amv_value_or_view_class<ArrayType>::value && !has_scalar_or_string_value_type<ArrayType>::value>
 h5_write(h5::group gr, std::string name, ArrayType const& a) {
  if (a.is_empty()) TRIQS_RUNTIME_ERROR << " Cannot save an empty array into hdf5";
  auto gr2 = gr.create_group(name);
  gr2.write_triqs_hdf5_data_scheme(a);
  // save the shape
  array<int, 1> sha(ArrayType::rank);
  for (int u = 0; u < ArrayType::rank; ++u) sha(u) = a.shape()[u];
  h5_write(gr2, "shape", sha);
#ifndef __cpp_generic_lambdas
  foreach(a, h5_impl::_save_lambda<ArrayType>{a, gr2});
#else
  foreach(a, [&](auto... is) { h5_write(gr2, h5_impl::_h5_name(is...), a(is...)); });
#endif
 }
Exemplo n.º 3
0
size_t tmdPreloadChunk(tmd_data *data, wchar_t *path, uint_fast16_t content_index) { //loads tmd chunk records and returns total chunks size of content index type on success
	FIL fil;
	size_t offset, size = 0;
	uint_fast16_t content_count, chunk_count;
	uint8_t hash[SHA_256_SIZE];
	
	if (FileOpen(&fil, path, 0) && (offset = tmdHeaderOffset(data->sig_type))) {
		size = (content_count = __builtin_bswap16(data->header.content_count)) * sizeof(tmd_content_chunk);
		if (!data->content_chunk)
			data->content_chunk = __builtin_alloca(size);
		if (FileSeek(&fil, offset + sizeof(data->header) + sizeof(data->content_info)) && FileRead2(&fil, data->content_chunk, size) == size) {
			size = 0;
			for (uint_fast16_t info_index = 0, chunk_index = 0; chunk_index < content_count; info_index++) {
				chunk_count = __builtin_bswap16(data->content_info[info_index].content_command_count);
				sha(hash, &data->content_chunk[chunk_index], chunk_count * sizeof(tmd_content_chunk), SHA_256_MODE);
				if (memcmp(hash, data->content_info[chunk_index].content_chunk_hash, sizeof(hash))) {
					size = 0;
					break;
				}
				for (; chunk_count > 0; chunk_index++, chunk_count--) {
					if (content_index == CONTENT_INDEX_ALL || content_index == data->content_chunk[chunk_index].content_index)
						size += __builtin_bswap32(data->content_chunk[chunk_index].content_size_lo);
				}
			}
		} else size = 0;
		FileClose(&fil);
	}
	return size;
}
Exemplo n.º 4
0
int
sign(char* private_key_path, unsigned char *msg, int msg_len,
     unsigned char *sig, unsigned int *sig_len)
{

    //Load private key
    FILE *fp = fopen(private_key_path, "r");
    if(!fp) {
        DEBUGMSG(ERROR, "Could not find private key\n");
        return 0;
    }
    RSA *rsa = (RSA *) PEM_read_RSAPrivateKey(fp,NULL,NULL,NULL);
    fclose(fp);
    if(!rsa) return 0;

    unsigned char md[SHA256_DIGEST_LENGTH];
    sha(msg, msg_len, md);

    //Compute signatur
    int err = RSA_sign(NID_sha256, md, SHA256_DIGEST_LENGTH, (unsigned char*)sig, (unsigned int*)sig_len, rsa);
    if(!err){
        printf("Error: %ul\n", (unsigned int)ERR_get_error());
    }
    RSA_free(rsa);
    return err;
}
Exemplo n.º 5
0
QString FLManagerModules::contentStaticDir( const QString & n ) {
  QString str_ret( contentFS( staticDirFiles_ + "/" + n ) );

  if ( !str_ret.isEmpty() ) {

    QString sha( FLUtil::sha1( str_ret ) );
    QString * s = 0;
    if ( dictKeyFiles && ( s = ( *dictKeyFiles )[ n ] ) && *s == sha )
      return QString::null;
    else if ( dictKeyFiles && n.endsWith( ".qs" ) )
      dictKeyFiles->replace( n, new QString( sha ) );

    if ( n.endsWith( ".mtd" ) ) {
      FLTableMetaData * mtd;
      QDomDocument doc( n );
      QDomElement docElem;

      if ( FLUtil::domDocumentSetContent( doc, str_ret ) ) {
        FLManager * mgr = db_->manager();
        docElem = doc.documentElement();
        mtd = mgr->metadata( &docElem, true );

        if ( !mtd || mtd->isQuery() )
          return str_ret;

        if ( !mgr->existsTable( mtd->name() ) )
          mgr->createTable( mtd );
        else if ( db_->canRegenTables() )
          db_->regenTable( mtd->name(), mtd );
      }
    }
  }

  return str_ret;
}
Exemplo n.º 6
0
QVariant FLManager::fetchLargeValue(const QString &refKey) const
{
  if (refKey.left(3) != "RK@")
    return QVariant();

  QString sha(refKey.section('@', 2, 2));
  QVariant *cachedV = cacheLargeValues_->find(sha);
  if (cachedV)
    return QVariant(*cachedV);

  QString tableLarge(QString::fromLatin1("fllarge"));
  if (!existsTable(tableLarge))
    return QVariant();

  QSqlQuery qryLarge(QString::null, db_->db());
  if (qryLarge.exec(QString::fromLatin1("SELECT contenido FROM ") + tableLarge +
                    QString::fromLatin1(" WHERE refkey='") + refKey + QString::fromLatin1("'")) &&
      qryLarge.next()) {
    QVariant v(qryLarge.value(0));
    if (v.isValid())
      cacheLargeValues_->insert(sha, new QVariant(v));
    return v;
  }
  return QVariant();
}
Exemplo n.º 7
0
bool StateInfo::isChanged(uint what) const
{
    bool ret = false;
    if (what & SHA)
        ret = (sha(true) != sha(false));

    if (!ret && (what & FILE_NAME))
        ret = (fileName(true) != fileName(false));

    if (!ret && (what & DIFF_TO_SHA))
        ret = (diffToSha(true) != diffToSha(false));

    if (!ret && (what & ALL_MERGE_FILES))
        ret = (allMergeFiles(true) != allMergeFiles(false));

    return ret;
}
Exemplo n.º 8
0
bool Unique_Key::set_key(std::string key_in) {
	unsigned char digest[24];
	SHA3 sha(16);
	sha.CalculateDigest(digest, (const byte*)key_in.c_str(), key_in.length());
	this->key.assign((const char*)digest);
	this->keylen = key_in.length();
	return true;
}
Exemplo n.º 9
0
void Scene::mousePressEvent(QGraphicsSceneMouseEvent * mouseEvent) {
    bool isClickOnGraphic = false;
    for(Graphics*shape : *shapes){
           QRectF sha((shape->getBoundingBox()).llx(), (shape->getBoundingBox()).lly(), (shape->getBoundingBox()).getL(),(shape->getBoundingBox()).getW());
           isClickOnGraphic = isClickOnGraphic || sha.contains(mouseEvent->scenePos());
        }
    if(!isClickOnGraphic){
        for(Graphics*shape : *shapes){
            shape->setAllUnSelected();
        }
    }
    this->update();
    QGraphicsScene::mousePressEvent(mouseEvent);
}
Exemplo n.º 10
0
QString FLManager::storeLargeValue(FLTableMetaData *mtd, const QString &largeValue)
{
  if (largeValue.left(3) == "RK@" || !mtd)
    return QString::null;

  QString tableName(mtd->name());
  if (isSystemTable(tableName))
    return QString::null;

  QString tableLarge(QString::fromLatin1("fllarge"));
  /*if (!existsTable(tableLarge)) {
    FLTableMetaData *mtdLarge = new FLTableMetaData(tableLarge, tableLarge);
    FLFieldMetaData *fieldLarge = new FLFieldMetaData("refkey", "refkey", false, true, QVariant::String, 100);
    mtdLarge->addFieldMD(fieldLarge);
    fieldLarge = new FLFieldMetaData("sha", "sha", true, false, QVariant::String, 50);
    mtdLarge->addFieldMD(fieldLarge);
    fieldLarge = new FLFieldMetaData("contenido", "contenido", true, false, QVariant::StringList);
    mtdLarge->addFieldMD(fieldLarge);
    FLTableMetaData *mtdAux = createTable(mtdLarge);
    mtd->insertChild(mtdLarge);
    if (!mtdAux)
      return QString::null;
  }
*/
  QString sha(FLUtil::sha1(largeValue));
  QString refKey(QString::fromLatin1("RK@") + tableName.left(50) + QString::fromLatin1("@") + sha);
  QSqlCursor curLarge(tableLarge, true, db_->dbAux());
  QSqlRecord *bufLarge;
  curLarge.setFilter(QString::fromLatin1("refkey='") + refKey +
                     QString::fromLatin1("'"));
  curLarge.select();
  if (curLarge.next()) {
    if (curLarge.value("sha").toString() != sha) {
      bufLarge = curLarge.primeUpdate();
      bufLarge->setValue("sha", sha);
      bufLarge->setValue("contenido", largeValue);
      curLarge.update();
    }
  } else {
    bufLarge = curLarge.primeInsert();
    bufLarge->setValue("refkey", refKey);
    bufLarge->setValue("sha", sha);
    bufLarge->setValue("contenido", largeValue);
    curLarge.insert();
  }

  return refKey;
}
Exemplo n.º 11
0
// Build a finished message, see 7.6.9
void buildFinished(SSL& ssl, Finished& fin, const opaque* sender) 
{
    // store current states, building requires get_digest which resets state
    MD5 md5(ssl.getHashes().get_MD5());
    SHA sha(ssl.getHashes().get_SHA());

    if (ssl.isTLS())
        buildFinishedTLS(ssl, fin, sender);
    else {
        buildMD5(ssl, fin, sender);
        buildSHA(ssl, fin, sender);
    }

    // restore
    ssl.useHashes().use_MD5() = md5;
    ssl.useHashes().use_SHA() = sha;
}
Exemplo n.º 12
0
 std::c14::enable_if_t<is_amv_value_or_view_class<ArrayType>::value && !has_scalar_or_string_value_type<ArrayType>::value>
 h5_read(h5::group gr, std::string name, ArrayType& a) {
  static_assert(!std::is_const<ArrayType>::value, "Cannot read in const object");
  auto gr2 = gr.open_group(name);
  // TODO checking scheme...
  // load the shape
  auto sha2 = a.shape();
  array<int, 1> sha;
  h5_read(gr2, "shape", sha);
  if (first_dim(sha) != sha2.size())
   TRIQS_RUNTIME_ERROR << " array<array<...>> load : rank mismatch. Expected " << sha2.size()<< " Got " << first_dim(sha);
  for (int u = 0; u < sha2.size(); ++u) sha2[u] = sha(u);
  if (a.shape() != sha2) a.resize(sha2);
#ifndef __cpp_generic_lambdas
  foreach(a, h5_impl::_load_lambda<ArrayType>{a, gr2});
#else
  foreach(a, [&](auto... is) { h5_read(gr2, h5_impl::_h5_name(is...), a(is...)); });
#endif
 }
Exemplo n.º 13
0
// build certificate hashes
void build_certHashes(SSL& ssl, Hashes& hashes)
{
    // store current states, building requires get_digest which resets state
    MD5 md5(ssl.getHashes().get_MD5());
    SHA sha(ssl.getHashes().get_SHA());

    if (ssl.isTLS()) {
        ssl.useHashes().use_MD5().get_digest(hashes.md5_);
        ssl.useHashes().use_SHA().get_digest(hashes.sha_);
    }
    else {
        buildMD5_CertVerify(ssl, hashes.md5_);
        buildSHA_CertVerify(ssl, hashes.sha_);
    }

    // restore
    ssl.useHashes().use_MD5() = md5;
    ssl.useHashes().use_SHA() = sha;
}
Exemplo n.º 14
0
int get_auth_level(){
	char *IP, *URL, *id, *id_ori, *key, *salt;
	int level;
	salt = calloc(128, 1);
	IP = getenv("REMOTE_ADDR");
	if(!IP) die(BAD_IP);
	URL = getenv("HTTP_REFERER");
	if(!URL) die(BAD_URL);
	key = get_key();
	if(!key) die(BAD_SERV);
	snprintf(salt, 128, "$5$%s$", IP);
	id = sha(URL, salt);
	id = strrchr(id, '$') + 1;
	id_ori = get_id(key, &level);
	if(!id_ori) die(NO_REG);
	if(strcmp(id, id_ori)) die(BAD_SERV);
	free(salt);
	return(level);
}
Exemplo n.º 15
0
int main(int argc, char ** argv)
{
	int retv = 0;

	if (argc < 2) {
		usage();
		return 0;
	}

	if (init_param(argc, argv) < 0)
		return -1;

	if (open_crypto_dev() < 0)
		return -1;

	if (crypto_method == CRYPTO_SHA1){
		retv = sha();
		return retv;
	}

	if (crypto_method == CRYPTO_MD5){
		retv = md5();
		return retv;
	}

	if (autotest_flag) {
		retv = auto_test(algoname);
		return retv;
	}

	if (crypto_method == CRYPTO_ENCRYPTE) {
		if (do_encryption(algoname) < 0)
			return -1;
	} else {
		if (do_decryption(algoname) < 0)
			return -1;
	}

	close_crypto_dev();

	return 0;
}
Exemplo n.º 16
0
int boot1_check(rawnand nand)
{
	u8 *buffer;
	u8 hash[20];
	
	buffer = malloc(BYTES_PER_BLOCK);
	if(!buffer)
		fatal("Unable to allocate boot1 buffer");
	
	rawnand_read_block(nand, buffer, 0);
	sha(buffer, 0x17800, hash);
	free(buffer);

	if (memcmp(hash, boot1_hash, 0x14)) {
		fprintf(stderr, "boot1: hash verification failed.\n");
		return WIIFSCK_INVAL;
	}

	return WIIFSCK_OK;
}
Exemplo n.º 17
0
size_t tmdPreloadHeader(tmd_data *data, wchar_t *path) { //loads tmd header, validatas content info hash and returns content chunks size on success
	File fil;
	size_t offset;
	tmd_data data_tmp;
	uint8_t hash[32];
	
	if (!FileOpen(&fil, path, 0) || (
		(FileRead2(&fil, &data_tmp.sig_type, sizeof(data_tmp.sig_type)) != sizeof(data_tmp.sig_type) ||
		(offset = tmdHeaderOffset(data_tmp.sig_type)) == 0 ||
		!FileSeek(&fil, offset) ||
		FileRead2(&fil, &data_tmp.header, sizeof(data_tmp.header) + sizeof(data_tmp.content_info)) != sizeof(data_tmp.header) + sizeof(data_tmp.content_info)) &&
		(FileClose(&fil) || 1)
	)) return 0;
	FileClose(&fil);
	sha(hash, &data_tmp.content_info, sizeof(data_tmp.content_info), SHA_256_MODE);
	if (memcmp(hash, data_tmp.header.content_info_hash, sizeof(hash))) return 0;
	*data = data_tmp;
	data->content_chunk = NULL;
	return __builtin_bswap16(data->header.content_count) * sizeof(tmd_content_chunk);
}
Exemplo n.º 18
0
Integer HashPointMessage(const ECP& ec, const ECPPoint& R,
	const byte* message, int mlen, bool compress = false)
{
	const int digestsize = 256/8;
	SHA3 sha(digestsize);

	int len = ec.EncodedPointSize();
	byte *buffer = new byte[len];
	ec.EncodePoint(buffer, R, compress);
	sha.Update(buffer, len);
	delete[] buffer;

	sha.Update(message, mlen);

	byte digest[digestsize];
	sha.Final(digest);
	
	Integer ans;
	ans.Decode(digest, digestsize);
	return ans;
}
Exemplo n.º 19
0
static QByteArray fileHash(QFile &file)
{
	QByteArray hash = QByteArray::fromHex(g_seed);
	QByteArray salt = QByteArray::fromHex(g_salt);
	
	if(file.isOpen() && file.reset())
	{
		QByteArray data = file.readAll();
		QCryptographicHash sha(QCryptographicHash::Sha1);
		QCryptographicHash md5(QCryptographicHash::Md5);

		for(int r = 0; r < 8; r++)
		{
			sha.reset(); md5.reset();
			sha.addData(hash); md5.addData(hash);
			sha.addData(data); md5.addData(data);
			sha.addData(salt); md5.addData(salt);
			hash = sha.result() + md5.result();
		}
	}

	return hash;
}
Exemplo n.º 20
0
void QgsAuthSslConfigWidget::setSslCertificate( const QSslCertificate &cert, const QString &hostport )
{
  if ( mDisabled )
  {
    return;
  }
  if ( cert.isNull() )
  {
    return;
  }
  mCert = cert;

  if ( !hostport.isEmpty() )
  {
    setSslHost( hostport );
  }

  QString sha( QgsAuthCertUtils::shaHexForCert( cert ) );
  QgsAuthConfigSslServer config(
    QgsAuthManager::instance()->getSslCertCustomConfig( sha, hostport.isEmpty() ? sslHost() : hostport ) );

  emit certFoundInAuthDatabase( !config.isNull() );

  lblLoadedConfig->setVisible( true );
  if ( !config.isNull() )
  {
    loadSslCustomConfig( config );
    leCommonName->setStyleSheet( QgsAuthGuiUtils::greenTextStyleSheet() );
  }
  else
  {
    lblLoadedConfig->setText( configNotFoundText_() );
    leCommonName->setText( QgsAuthCertUtils::resolvedCertName( mCert ) );
    leCommonName->setStyleSheet( QgsAuthGuiUtils::orangeTextStyleSheet() );
  }
  validateHostPortText( leHost->text() );
}
Exemplo n.º 21
0
static ERL_NIF_TERM
sha256(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    return sha(env, argc, argv, hd256_init, hd2xx_update, hd256_final);
}
Exemplo n.º 22
0
static ERL_NIF_TERM
sha512(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    return sha(env, argc, argv, hd512_init, hd5xx_update, hd512_final);
}
bool Import_PwManager::importDatabase(QWidget* GuiParent, IDatabase* db){	
	database=db;
	QFile* file=openFile(GuiParent,identifier(),QStringList()<<tr("PwManager Files (*.pwm)")<<tr("All Files (*)"));
	if(!file)return false;
	QString password=getPassword(GuiParent);
	if(password.isEmpty()){delete file; return false;}
	char* buffer=NULL;
	int offset=0;
	int len=0;
	if((len=file->size())){
		buffer=new char[len];
	}
	else {
		QMessageBox::critical(GuiParent,tr("Import Failed"),tr("File is empty."));
		delete file;
		return false;
	}
	file->read(buffer,len);
	file->close();
	delete file;
	if(QString::fromAscii(buffer,17)!="PWM_PASSWORD_FILE")
	{QMessageBox::critical(GuiParent,tr("Import Failed"),tr("File is no valid PwManager file.")); return false;}
	offset+=17;
	if(buffer[offset]!=0x05)
	{QMessageBox::critical(GuiParent,tr("Import Failed"),tr("Unsupported file version.")); return false;}
	offset++;
	if(buffer[offset]!=0x01)
	{QMessageBox::critical(GuiParent,tr("Import Failed"),tr("Unsupported hash algorithm.")); return false;}
	offset++;
	if(buffer[offset]!=0x01)
	{QMessageBox::critical(GuiParent,tr("Import Failed"),tr("Unsupported hash algorithm.")); return false;}
	offset++;
	if(buffer[offset]!=0x01)
	{QMessageBox::critical(GuiParent,tr("Import Failed"),tr("Unsupported encryption algorithm.")); return false;}
	offset++;
	if(buffer[offset]==0x00)Compression=0;
	if(buffer[offset]==0x01)Compression=1;
	if(buffer[offset]==0x02)Compression=2;
	///@TODO Compression
	if(buffer[offset])
	{QMessageBox::critical(GuiParent,tr("Import Failed"),tr("Compressed files are not supported yet.")); return false;}
	offset++;
	if(buffer[offset]==0x00)KeyFlag=true;
	else KeyFlag=false;
	offset++;
	//Reserved Bytes (64)
	offset+=64;
	memcpy(KeyHash,buffer+offset,20);
	offset+=20;
	memcpy(DataHash,buffer+offset,20);
	offset+=20;
	
	Blowfish blowfish;
	int pwlen=password.length();
	byte* Key=new byte[pwlen];
	byte* xml=new byte[len-offset+1];
	xml[len-offset]=0;
	memcpy(Key,password.toAscii(),pwlen);
	QCryptographicHash sha(QCryptographicHash::Sha1);
	sha.addData((const char*)Key,pwlen);
	QByteArray key_hash = sha.result();
	if(memcmp(key_hash.constData(),KeyHash,20)){
		delete[] Key;
		delete [] buffer;
		QMessageBox::critical(GuiParent,tr("Import Failed"),tr("Wrong password."));
		return false;
	}
	blowfish.bf_setkey(Key,password.length());
	blowfish.bf_decrypt(xml,(byte*)buffer+offset,len-offset);
	delete [] Key;
	delete [] buffer;
	sha.reset();
	sha.addData((const char*)xml,strlen((char*)xml)-1);
	QByteArray content_hash = sha.result();
	if(memcmp(content_hash.constData(),DataHash,20)){
		delete [] xml;
		QMessageBox::critical(GuiParent,tr("Import Failed"),tr("File is damaged (hash test failed)."));
		return false;
	}
	
	if(!parseXmlContent((char*)xml)){
		delete [] xml;
		QMessageBox::critical(GuiParent,tr("Import Failed"),tr("Invalid XML data (see stdout for details).")); return false;
	}
	return true;
}
Exemplo n.º 24
-1
int
verify(char* public_key_path, unsigned char *msg, int msg_len,
       unsigned char *sig, unsigned int sig_len)
{
    //Load public key
    FILE *fp = fopen(public_key_path, "r");
    if(!fp) {
        printf("Could not find public key\n");
        return 0;
    }

    RSA *rsa = (RSA *) PEM_read_RSA_PUBKEY(fp, NULL, NULL, NULL);
    if(!rsa) return 0;
    fclose(fp);

    //Compute Hash
    unsigned char md[SHA256_DIGEST_LENGTH];
    sha(msg, msg_len, md);

    //Verify signature
    int verified = RSA_verify(NID_sha256, md, SHA256_DIGEST_LENGTH, (unsigned char*)sig, (unsigned int)sig_len, rsa);
    if(!verified){
        printf("Error: %ul\n", (unsigned int)ERR_get_error());
    }
    RSA_free(rsa);
    return verified;
}