void assign_values(int month, int day, int *number_direct_coefficients)
{
	int hour1;
	double st; /* solar time */
	double sd;
	double alt2_rise, alt2_set;
	sd = sdec(jdate(month, day));
	alt2_rise = f_salt(sd, radians(2.0));
	alt2_set = 24 - f_salt(sd, radians(2.0));
	for (hour1 = 0; hour1< 24; hour1++){
		st = hour1;
		if (((hour1 - 0.5)<alt2_rise) && ((hour1 + 0.5) > alt2_rise)){ st = alt2_rise; }
		if (((hour1 - 0.5)<alt2_set) && ((hour1 + 0.5) > alt2_set)){ st = alt2_set; }

		if (degrees(salt(sd, st)) > 1.999){
			direct_pts[*number_direct_coefficients][0] = (float)st;
			direct_pts[*number_direct_coefficients][1] = (float)degrees(salt(sd, st));
			if (direct_pts[*number_direct_coefficients][1] <2.001){ direct_pts[*number_direct_coefficients][1] = 2; }
			direct_pts[*number_direct_coefficients][2] = (float)degrees(sazi(sd, st));
			direct_calendar[month][hour1][0] = direct_pts[*number_direct_coefficients][0];
			direct_calendar[month][hour1][1] = direct_pts[*number_direct_coefficients][1];
			direct_calendar[month][hour1][2] = direct_pts[*number_direct_coefficients][2];
			*number_direct_coefficients = *number_direct_coefficients + 1;
		}
		else{
			direct_calendar[month][hour1][0] = (float)st;
			direct_calendar[month][hour1][1] = (float)degrees(salt(sd, st));
			direct_calendar[month][hour1][2] = (float)degrees(sazi(sd, st));
		}
	}
}
Esempio n. 2
0
void test4saltImage(int argc,char** argv){
	srand( cv::getTickCount() );
	cv::Mat image=cv::imread( inputImagePath );
	salt(&image,3000);
	IplImage temp4image=image;
	alert_win( &temp4image );
}
/**
* A fully parametrized symmetric string encryption function
* Encrypts using the specified algorithm and CBC+PKCS7.
* Format as follows (//TODO ASN.1 Notation required):
* Base64
* {
* n bytes salt (parameter)
* 32 bytes IV
* message
* }
*/
string cryptTextUnauthenticated(string& plaintext, string& password, bool decrypt = false, string& algorithm = "Twofish", uint saltSize = 24)
{
    AutoSeeded_RNG rng;
    string fullAlgorithmName = algorithm + "/CBC/PKCS7";

    //Generate a random salt
    SecureVector<byte> salt(rng, saltSize);

    //Check whether whe have to decrypt
    Cipher_Dir direction = ENCRYPTION;
    if(decrypt) {direction = DECRYPTION;}

    SymmetricKey key = OctetString(hashRaw("SHA-256", password, salt));
    InitializationVector iv(rng, 32);

    Pipe encryptionPipe(new Chain(get_cipher(fullAlgorithmName, key, iv, direction)));
    encryptionPipe.start_msg();
    encryptionPipe.write(plaintext);
    encryptionPipe.end_msg();
    SecureVector<byte> encryptedData = encryptionPipe.read_all(0);

    Pipe base64Pipe(new Base64_Encoder);
    base64Pipe.start_msg ();
    base64Pipe.write(salt);
    base64Pipe.write(iv);
    base64Pipe.write(encryptedData);
    base64Pipe.end_msg();

    return base64Pipe.read_all_as_string (0);
}
Esempio n. 4
0
std::string generate_passhash9(const std::string& pass,
                               RandomNumberGenerator& rng,
                               uint16_t work_factor,
                               uint8_t alg_id)
   {
   BOTAN_ARG_CHECK(work_factor > 0 && work_factor < 512, "Invalid Passhash9 work factor");

   std::unique_ptr<MessageAuthenticationCode> prf = get_pbkdf_prf(alg_id);

   if(!prf)
      throw Invalid_Argument("Passhash9: Algorithm id " +
                             std::to_string(alg_id) +
                             " is not defined");

   PKCS5_PBKDF2 kdf(prf.release()); // takes ownership of pointer

   secure_vector<uint8_t> salt(SALT_BYTES);
   rng.randomize(salt.data(), salt.size());

   const size_t kdf_iterations = WORK_FACTOR_SCALE * work_factor;

   secure_vector<uint8_t> blob;
   blob.push_back(alg_id);
   blob.push_back(get_byte(0, work_factor));
   blob.push_back(get_byte(1, work_factor));
   blob += salt;
   blob += kdf.derive_key(PASSHASH9_PBKDF_OUTPUT_LEN,
                          pass,
                          salt.data(), salt.size(),
                          kdf_iterations).bits_of();

   return MAGIC_PREFIX + base64_encode(blob);
   }
int main()
{
	// open the image
	cv::Mat image= cv::imread("boldt.jpg",1);
    // image is resized for book printing
	cv::resize(image, image, cv::Size(), 0.6, 0.6);

	// call function to add noise
	salt(image,3000);

	// display result
	cv::namedWindow("Image");
	cv::imshow("Image",image);

	// write on disk
	cv::imwrite("salted.bmp",image);

	cv::waitKey();

	// test second version
	image= cv::imread("boldt.jpg",0);
    // image is resized for book printing
	cv::resize(image, image, cv::Size(), 0.6, 0.6);

	salt2(image, 500);

	cv::namedWindow("Image");
	cv::imshow("Image",image);

	cv::waitKey();

	return 0;
}
Esempio n. 6
0
bool PasswordModule::GeneratePassHash(const wchar_t *userName, const wchar_t *passWord, std::string &passWordHash)
{
    if (wcsnlen(userName, 51) > 50 || wcsnlen(passWord, 51) > 50) {
        sLog.Error("PasswordModule", "username or password is simply to long");
        return false;
    }

    std::wstring salt(userName);

    Utils::Strings::trim(salt, true, true);     // comparable to the ".strip" function in python.
    Utils::Strings::toLowerCase(salt);

    int saltLen = (int)salt.size() * 2;
    uint8 * saltChar = (uint8*)&salt[0];

    std::wstring init(passWord);
    init += salt;

    int saltInitLen = (int)init.size() * 2;
    uint8 * saltInitChar = (uint8*)&init[0];

    #ifndef WIN32
        saltChar = wchar_tToUtf16(saltChar, salt.size());
        saltInitChar = wchar_tToUtf16(saltInitChar, init.size());
    #endif

    ShaModule::SHAobject shaObj;

    ShaModule::sha_init(&shaObj);
    ShaModule::sha_update(&shaObj, saltInitChar, saltInitLen);

    int daylySaltLen = SHA_DIGEST_SIZE + saltLen;

    // allocate buffer for the hashing, this way its only allocated once.
    uint8 * uDaylySalt = (uint8 *)malloc(daylySaltLen);   // first part of the data string
    uint8 * uDaylySaltPart = &uDaylySalt[SHA_DIGEST_SIZE];      // second part of the data string

    for (int i = 0; i < 1000; i++)
    {
        ShaModule::sha_digest(&shaObj, uDaylySalt);
        memcpy(uDaylySaltPart, saltChar, saltLen);

        ShaModule::sha_init(&shaObj);
        ShaModule::sha_update(&shaObj, uDaylySalt, daylySaltLen);
    }

    free(uDaylySalt);

    ShaModule::sha_final(mDigest, &shaObj);

    if (passWordHash.size() != 0)
        passWordHash = "";

    passWordHash.append((char*)mDigest, SHA_DIGEST_SIZE);

    return true;
}
Esempio n. 7
0
void CImageAnalysis::OnBnClickedsaltshow()
{
	Mat image;
	image= imread("F:\\Lena.bmp",1);
	salt(image, 10000);
	namedWindow("image");
	imshow("image",image);
	waitKey(0);
}
Esempio n. 8
0
bool MaItem::load(const QString& filename)
{
	bool res = false;

	if (!filename.isEmpty())
		mFilename = filename;

	mRelPath.clear();
	mRelPath = relPath();
#ifdef _DEBUG
//	qDebug() << absPath();
#endif  // _DEBUG

	QFile file(absPath());
	if (file.open(QIODevice::ReadOnly))
	{
		QTextStream in(&file);
		in.setCodec("UTF-8");
		parseConfigLine(in.readLine());
		if (mIsEncrypted)
		{
			QByteArray s = in.readAll().toAscii();
			_engine->encrypt(s);
			QString s2(s);
			int i = s2.indexOf("\n");
			if (i > -1)
			{
				mCaption = s2.left(i);
				mNotes = s2.right(s2.length() - i - 1);
			}
		}
		else
		{
			mCaption = in.readLine();
			mNotes = in.readAll();
		}
		file.close();
		res = true;
	}

	// Loading the password from the password file:
	QFile file2(absPathToFilename(kPathwordFilename));
	if (file.exists() && file2.open(QIODevice::ReadOnly))
	{
		QTextStream in(&file2);
		in.setCodec("UTF-8");
		QByteArray ba = in.readAll().toAscii();
		QByteArray salt(QString(_engine->passwordEncryptionSalt()).toAscii());
		_engine->encrypt(ba, _engine->passwordEncryptionKey().toAscii(), salt);
		mPassword = ba;
		mPasswordDirty = false;
	}

	return res;
}
int main(int argc, char ** argv) {
  cv::Mat img = cv::imread(argv[1]);

  if(!img.data) return -1;

  salt(img, 3000);
  cv::namedWindow("Salted Image");
  cv::imshow("Salted Image", img);
  cv::waitKey(0);
  return 0;
}
Esempio n. 10
0
int main() {
	std::string
		str_winName = "Image";
	cv::Mat img = cv::imread("Images/boldt.jpg");
	cv::Mat result_img;
	salt(img, result_img, 3000);

	cv::namedWindow(str_winName);
	cv::imshow(str_winName, result_img);
	cv::waitKey(0);
	return 1;
}
Esempio n. 11
0
std::string rpc::genSalt()
{
    int size = 32;
    std::ostringstream ss;
    std::vector<unsigned char> salt(size, 0);
    urand.generate(&salt[0], size);

    for (int i = 0; i < size; i++)
        ss << std::hex << std::setw(2) << std::setfill('0') << (int)salt[i];

    return ss.str();
}
Esempio n. 12
0
QByteArray Crypto::generateSalt()
{
    const int salt_bytes_count = 5;

#ifndef NO_QCA
    return QCA::Random::randomArray(salt_bytes_count).toByteArray();
#else
    QByteArray salt("");
    for(int i = 0; i < salt_bytes_count; i++)
        salt.append(char(randInt(0, 255)));
    return salt;
#endif
}
Esempio n. 13
0
void MaItem::save(bool onlyWhenDirty)
{
	if (!onlyWhenDirty || mDirty)
	{
		bool encrypt = isListEncrypted();
		if (mFilename.isEmpty())
			mFilename = mParentItem->nextChildFilename();
		QFile file(absPath());

		if (file.open(QIODevice::WriteOnly))
		{
			QTextStream out(&file);
			out.setCodec("UTF-8");
			out << configLine(encrypt);
			out << "\n";
			if (encrypt)
			{
				QByteArray s(mCaption.toAscii());
				s.append("\n");
				s.append(mNotes.toAscii());
				_engine->encrypt(s);
				out << s;
			}
			else
			{
				out << mCaption;
				out << "\n";
				out << mNotes;
			}
			file.close();
			mDirty = false;
		}
	}

	// Saving the password:
	if ((!onlyWhenDirty || mPasswordDirty) && !mPassword.isEmpty())
	{
		QFile pwdFile(absPathToFilename(kPathwordFilename));
		if (pwdFile.open(QIODevice::WriteOnly))
		{
			QTextStream out(&pwdFile);
			out.setCodec("UTF-8");
			QByteArray ba(mPassword.toAscii());
			QByteArray salt(QString(_engine->passwordEncryptionSalt()).toAscii());
			_engine->encrypt(ba, _engine->passwordEncryptionKey().toAscii(), salt);
			out << ba;
			pwdFile.close();
			mPasswordDirty = false;
		}
	}
}
Esempio n. 14
0
QString ClientConfiguration::toBackup(QString const& password) const {
	QByteArray encryptionKey(BACKUP_ENCRYPTION_KEY_BYTES, 0x00);

	// Generate a Salt
	QByteArray salt(BACKUP_SALT_BYTES, 0x00);
	randombytes_buf(salt.data(), BACKUP_SALT_BYTES);

	// Convert the password into bytes
	QByteArray password8Bit = password.toUtf8();

	// Generate the encryption key for the Backup from the Salt and the Password
	PKCS5_PBKDF2_HMAC(reinterpret_cast<unsigned char*>(password8Bit.data()), password8Bit.size(), reinterpret_cast<unsigned char*>(salt.data()), BACKUP_SALT_BYTES, BACKUP_KEY_PBKDF_ITERATIONS, BACKUP_ENCRYPTION_KEY_BYTES, reinterpret_cast<unsigned char*>(encryptionKey.data()));

	QByteArray nonceBytes(crypto_stream_NONCEBYTES, 0x00);

	// The backup content
	QByteArray clientId(IdentityHelper::uint64ToIdentityString(getClientIdentity().getContactId()).toLatin1());
	if (clientId.size() != BACKUP_IDENTITY_BYTES) {
		throw InternalErrorException() << QString("Could not build backup - invalid client identity length (%1 vs. %2 Bytes).").arg(clientId.size()).arg(BACKUP_IDENTITY_BYTES).toStdString();
	}
	QByteArray clientSecKey(getClientLongTermKeyPair().getPrivateKey());
	if (clientSecKey.size() != PROTO_KEY_LENGTH_BYTES) {
		throw InternalErrorException() << QString("Could not build backup - invalid client secret key length (%1 vs. %2 Bytes).").arg(clientSecKey.size()).arg(PROTO_KEY_LENGTH_BYTES).toStdString();
	}

	QByteArray backup(salt);
	backup.append(clientId);
	backup.append(clientSecKey);

	// Compute Hash
	QByteArray controlHash(crypto_hash_sha256_BYTES, 0x00);
	crypto_hash_sha256(reinterpret_cast<unsigned char*>(controlHash.data()), reinterpret_cast<unsigned char*>(backup.data() + BACKUP_SALT_BYTES), BACKUP_IDENTITY_BYTES + PROTO_KEY_LENGTH_BYTES);
	backup.append(controlHash.left(BACKUP_HASH_BYTES));

	if (backup.size() != (BACKUP_SALT_BYTES + BACKUP_IDENTITY_BYTES + PROTO_KEY_LENGTH_BYTES + BACKUP_HASH_BYTES)) {
		throw InternalErrorException() << QString("Could not build backup - invalid packet length (%1 vs. %2 Bytes).").arg(clientSecKey.size()).arg(BACKUP_SALT_BYTES + BACKUP_IDENTITY_BYTES + PROTO_KEY_LENGTH_BYTES + BACKUP_HASH_BYTES).toStdString();
	}

	// The Backup is build from SALT + IDENTITY + KEY + HASH
	crypto_stream_xor(reinterpret_cast<unsigned char*>(backup.data() + BACKUP_SALT_BYTES), reinterpret_cast<unsigned char*>(backup.data() + BACKUP_SALT_BYTES), BACKUP_IDENTITY_BYTES + PROTO_KEY_LENGTH_BYTES + BACKUP_HASH_BYTES, reinterpret_cast<unsigned char*>(nonceBytes.data()), reinterpret_cast<unsigned char*>(encryptionKey.data()));

	// Encode in Base32
	return Base32::encodeBase32Sequence(backup);
}
Esempio n. 15
0
void UserDialog::addUser()
{
    QSqlRecord record;

    QSqlField id("id", QVariant::Int);
    QSqlField username("username", QVariant::String);
    QSqlField email("email", QVariant::String);
    QSqlField hashedPassword("hashed_password", QVariant::String);
    QSqlField salt("salt", QVariant::String);
    QSqlField roleId("role_id", QVariant::Int);

    id.setAutoValue(true);
    username.setValue(QVariant(usernameLineEdit->text()));
    email.setValue(QVariant(emailLineEdit->text()));

    QString generatedSalt = QUuid::createUuid().toString();
    QString generatedHashedPassword = QCryptographicHash::hash(passwordLineEdit->text().toAscii()
                                                               + generatedSalt.toAscii(),
                                                               QCryptographicHash::Sha1);

    hashedPassword.setValue(QVariant(generatedHashedPassword));
    salt.setValue(QVariant(generatedSalt));
    roleId.setValue(QVariant(getRoleId()));

    record.append(id);
    record.append(username);
    record.append(email);
    record.append(hashedPassword);
    record.append(salt);
    record.append(roleId);

    if(isFieldInputValid()
        && !isPasswordEmpty()
        && !userExists()
        && userModel->insertRecord(-1, record))
    {
        accept();
    }
    else
    {
        userModel->revertAll();
    }
}
Esempio n. 16
0
	void CEncrypt::CreateOwnerKey()
	{
        CryptoPP::RandomPool prng;

        CryptoPP::SecByteBlock salt(16);
        CryptoPP::OS_GenerateRandomBlock(false, salt, salt.size());
        prng.IncorporateEntropy(salt, salt.size());

        memcpy(m_anOwnerKey + 32, salt.data(), salt.size());

        CryptoPP::SHA256 hash;

        hash.Update( (unsigned char*) impl->m_sOwnerPassword.c_str(), impl->m_sOwnerPassword.length());
        hash.Update( m_anOwnerKey + 32, 8);
        hash.Update( m_anUserKey, 48);

        CryptoPP::SecByteBlock pHashData(hash.DigestSize());
        hash.Final(pHashData);

        if (MakeFileKey3(impl->m_sOwnerPassword, pHashData.data(), pHashData.size(), m_anUserKey, 48))
        {
            memcpy(m_anOwnerKey, pHashData.data(), pHashData.size());

            hash.Update( (unsigned char*) impl->m_sOwnerPassword.c_str(), impl->m_sOwnerPassword.length());
            hash.Update( m_anOwnerKey + 40, 8);
            hash.Update( m_anUserKey, 48);

            CryptoPP::SecByteBlock pHashKeyData(hash.DigestSize());
            hash.Final(pHashKeyData);

            MakeFileKey3(impl->m_sOwnerPassword, pHashKeyData.data(), pHashKeyData.size(), m_anUserKey, 48);
            unsigned char empty[16] = {};

            CryptoPP::AES::Encryption aesEncryption(pHashKeyData.data(), pHashKeyData.size());
            CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, empty);

            CryptoPP::StreamTransformationFilter stfEncryption(cbcEncryption, new CryptoPP::ArraySink( m_anOwnerEncryptKey, 32), CryptoPP::StreamTransformationFilter::NO_PADDING );
            stfEncryption.Put2(impl->m_anEncryptionKey, 32, 1, true);
            stfEncryption.MessageEnd();
        }
	}
Esempio n. 17
0
SqlConnection::ContainedData SqlConnection::getUserByName(const std::string &username)
{

    sqlite3_stmt * stat;
    prepareStatement(&stat, PREPARE_SELECT_USER_STATEMENT);

    sqlite3_bind_text(stat, 1, username.c_str(), username.length() +1, NULL);
    QMutexLocker l(&mutex);


    if(sqlite3_step(stat) !=SQLITE_ROW)
    {
        sqlite3_finalize(stat);
        throw SqlException("The user is not in the db");
    }
    ContainedData t;
    t.id = sqlite3_column_int(stat, 0);

    char * t1, *t2, *t3;
    t1 = (char*)sqlite3_column_text(stat,1);
    t2 = (char*)sqlite3_column_text(stat,2);
    t3 = (char*)sqlite3_column_text(stat,3);


    QString name(t1), pass(t2), salt(t3);

    t.name = name;
    t.password = pass;
    t.salt = salt;
    //free(t1);
    //free(t2);
    //free(t3);
    sqlite3_finalize(stat);


    return t;

}
void PSSR_MEM_Base::ComputeMessageRepresentative(RandomNumberGenerator &rng, 
	const byte *recoverableMessage, size_t recoverableMessageLength,
	HashTransformation &hash, HashIdentifier hashIdentifier, bool messageEmpty,
	byte *representative, size_t representativeBitLength) const
{
	assert(representativeBitLength >= MinRepresentativeBitLength(hashIdentifier.second, hash.DigestSize()));

	const size_t u = hashIdentifier.second + 1;
	const size_t representativeByteLength = BitsToBytes(representativeBitLength);
	const size_t digestSize = hash.DigestSize();
	const size_t saltSize = SaltLen(digestSize);
	byte *const h = representative + representativeByteLength - u - digestSize;

	SecByteBlock digest(digestSize), salt(saltSize);
	hash.Final(digest);
	rng.GenerateBlock(salt, saltSize);

	// compute H = hash of M'
	byte c[8];
	PutWord(false, BIG_ENDIAN_ORDER, c, (word32)SafeRightShift<29>(recoverableMessageLength));
	PutWord(false, BIG_ENDIAN_ORDER, c+4, word32(recoverableMessageLength << 3));
	hash.Update(c, 8);
	hash.Update(recoverableMessage, recoverableMessageLength);
	hash.Update(digest, digestSize);
	hash.Update(salt, saltSize);
	hash.Final(h);

	// compute representative
	GetMGF().GenerateAndMask(hash, representative, representativeByteLength - u - digestSize, h, digestSize, false);
	byte *xorStart = representative + representativeByteLength - u - digestSize - salt.size() - recoverableMessageLength - 1;
	xorStart[0] ^= 1;
	xorbuf(xorStart + 1, recoverableMessage, recoverableMessageLength);
	xorbuf(xorStart + 1 + recoverableMessageLength, salt, salt.size());
	memcpy(representative + representativeByteLength - u, hashIdentifier.first, hashIdentifier.second);
	representative[representativeByteLength - 1] = hashIdentifier.second ? 0xcc : 0xbc;
	if (representativeBitLength % 8 != 0)
		representative[0] = (byte)Crop(representative[0], representativeBitLength % 8);
}
Esempio n. 19
0
int main(int argc, char *argv[])
{
	QByteArray key("k04LbM3wLGa97rVm30Kyhas");
	QByteArray salt("013oPQLbplrz39g2oJElNyPQ20ms7H5v");

	QApplication app(argc, argv);
	QApplication::setStyle("plastique");
	Q_INIT_RESOURCE(marbles);

	_engine = new MaEngine();
	_engine->setEncryptKey(key);
	_engine->setEncryptSalt(salt);

    QString applicationDirPath(QCoreApplication::applicationDirPath());
    QFileInfo appFileInfo(QCoreApplication::applicationFilePath());
    const QString appFileName(appFileInfo.fileName());

    QString configPath;
#if defined(Q_WS_MAC)
    int pos = applicationDirPath.indexOf(QObject::tr("/%1.app/Contents/MacOS").arg(appFileName));
    if (pos > 0)
    {
        applicationDirPath.append("/../Resources");
    }
#endif // defined(Q_WS_MAC)

    configPath = QObject::tr("%1/%2.xml").arg(applicationDirPath).arg(appFileName);

    QFileInfo fi(configPath);
	if (fi.exists())
		_engine->loadConfig(fi.absoluteFilePath());

	_mainWindow = new MaMainWindow();
	QObject::connect(_engine, SIGNAL(openedStore()), 
		_mainWindow, SLOT(onOpenedStore()));
	_mainWindow->show();

	if (!_engine->lastOpenedStoreLocation().isEmpty())
		_engine->openStore(_engine->lastOpenedStoreLocation());
	else
		_mainWindow->onOpenStore();

//	_engine->store()->setPassword("skyout");

/*
	QString text("this is a test string.");
	QByteArray btext(text.toAscii());
	QByteArray key("THIS IS THE KEY");
	QByteArray salt;
	MaStore::encrypt(btext, key, salt);
	qDebug() << "text (encrypted)" << btext << ", salt=" << salt;
	MaStore::encrypt(btext, key, salt);
	qDebug() << "text (clear)" << btext << ", salt=" << salt;
	return 0;
*/

	int res = app.exec();
	_engine->onShuttingDown();
	delete _engine;
	return res;
}
Esempio n. 20
0
//-----------------------------------【main( )函数】------------------------------------------------------------------------------  
//      描述:控制台应用程序的入口函数,我们的程序从这里开始  
//--------------------------------------------------------------------------------------------------------------------------------  
int main(int agrc, char** agrv)
{


	initMain();//初始化

	//载入原图  
	g_srcImage = imread(".\\sourcePicture\\3.bmp");

	//添加噪音
	if (noice)
	{
		salt(g_srcImage);
		imwrite("./output/noice.bmp", g_gradBmp);
	}

	//定义一个Mat类型并给其设定ROI区域  
	//g_srcImage = g_srcImage(Rect(0, 0, 250, 250));

	//判断是否读取成功
	if (!g_srcImage.data)
	{
		cout << "读取图片srcImage时出错!\n";
		return false;
	}


	//将原图转换为灰度图  
	cvtColor(g_srcImage, g_srcGrayImage, CV_BGR2GRAY);

	ShowHelpText(g_srcGrayImage);

	//histGram(g_srcGrayImage);
	Edge edge1;
	Edge edge(g_srcGrayImage);//传值初始化
	edge.Init();//深入初始化
	//edge.edgeDection(1,NULL);

	//创建Canny检测的tracebar
	namedWindow("Canny检测");
	//namedWindow("listk1"); namedWindow("listk1&&listk2");
	createTrackbar("参数值:", "Canny检测", &g_cannyLowThreshold, 160, edge.on_Canny);
	namedWindow("g_mergImg");//, CV_WINDOW_NORMAL
	//createTrackbar("梯度:", "g_mergImg", &TH, 80, edge.edgeDection);	
	//createTrackbar("相似度:", "g_mergImg", &TH1, 40, edge.edgeDection);
	//createTrackbar("相似度:", "g_edge[1]", &g_di, 80, edge.listK);
	edge.edgeDection();
	//edge.edgeDection1();
	g_srcGrayImage.convertTo(g_srcGrayImage, CV_32F);

	if (xls)
	{
		edge.outXls(g_srcGrayImage, "./output/gray.xls");
		//outxlsInt(g_biGrad, "./output/bigrad.xls");
	}

	//cout << g_ltedge << endl;
	//将原图转换为灰度图
	//g_dstImage.convertTo(g_dstImage, CV_8UC1);
	//namedWindow("dst");
	//imshow("dst", g_dstImage);
	//显示梯度图片

	g_srcGrad.convertTo(g_gradBmp, CV_8UC1);
	imshow("梯度图", g_gradBmp);
	imwrite("./output/grad.bmp", g_gradBmp);





	//轮询获取按键信息,若按下Q,程序退出  
	while ((char(waitKey(1)) != 'q')) {}
	return 0;
}
Esempio n. 21
0
bool BotanWrapper::EncryptFile(QString Source, QString Destination)
{
    QFileInfo name = Source;
    QString base = name.baseName();
    QString encrypted1 = eoutput + base + ".gg";
    QString encrypted2 = toutput + base + ".twofish";
    QFile e(encrypted1);
    QFile t(encrypted2);

    try
    {
        //Setup the key derive functions
        PKCS5_PBKDF2 pbkdf2(new HMAC(new Keccak_1600));
        const u32bit PBKDF2_ITERATIONS = 700000;
qDebug() << "create keys";
        //Create the KEY and IV
        KDF* kdf = get_kdf("KDF2(SHA-512)");
AutoSeeded_RNG rng;
qDebug() << "create salt";
        SecureVector<byte> salt(256);
           rng.randomize(&salt[0], salt.size());
           mSalt = salt;
qDebug() << "create master key";
        //Create the master key
        SecureVector<byte> mMaster = pbkdf2.derive_key(128, mPassword.toStdString(), &mSalt[0], mSalt.size(),PBKDF2_ITERATIONS).bits_of();
        SymmetricKey mKey = kdf->derive_key(32, mMaster, "salt1");
        InitializationVector mIV = kdf->derive_key(16, mMaster, "salt2");
qDebug() << "start encryption";
        string inFilename = Source.toStdString();
        string outFilename = encrypted1.toStdString();
        std::ifstream inFile(inFilename.c_str());
        std::ofstream outFile(outFilename.c_str());


        Pipe pipe(get_cipher("AES-256/EAX", mKey, mIV,ENCRYPTION),new DataSink_Stream(outFile));
                outFile.write((const char*)mSalt.begin(), mSalt.size());
        pipe.start_msg();
        inFile >> pipe;
        pipe.end_msg();


        outFile.flush();
        outFile.close();
        inFile.close();


        QMessageBox msgBox;


/*****************TWOFISH ENCRYPTION********************/

qDebug() << "Twofish";
        //Setup the key derive functions
        PKCS5_PBKDF2 pbkdf3(new HMAC(new Skein_512));

        //Create the KEY and IV
        KDF* kdf2 = get_kdf("KDF2(Whirlpool)");
        SecureVector<byte> salt2(256);
           rng.randomize(&salt2[0], salt2.size());
           mSalt2 = salt2;

        //Create the master key
        SecureVector<byte> mMaster2 = pbkdf3.derive_key(128, mPassword2.toStdString(), &mSalt2[0], mSalt2.size(),PBKDF2_ITERATIONS).bits_of();
        SymmetricKey mKey2 = kdf2->derive_key(32, mMaster2, "salt1");
        InitializationVector mIV2 = kdf2->derive_key(16, mMaster2, "salt2");

        string inFilename2 = encrypted1.toStdString();
        string outFilename2 = encrypted2.toStdString();
        std::ifstream inFile2(inFilename2.c_str());
        std::ofstream outFile2(outFilename2.c_str());

        Pipe pipe2(get_cipher("Twofish/CFB", mKey2, mIV2,ENCRYPTION),new DataSink_Stream(outFile2));
                outFile2.write((const char*)mSalt2.begin(), mSalt2.size());
        pipe2.start_msg();
        inFile2 >> pipe2;
        pipe2.end_msg();


        outFile2.flush();
        outFile2.close();
        inFile2.close();


/**************************SERPENT ENCRYPTION*****************/

        //Create the KEY and IV
        KDF* kdf3 = get_kdf("KDF2(Tiger)");

        SecureVector<byte> salt3(256);
           rng.randomize(&salt3[0], salt3.size());
           mSalt3 = salt3;

        //Create the master key
        SecureVector<byte> mMaster3 = pbkdf2.derive_key(128, mPassword3.toStdString(), &mSalt3[0], mSalt3.size(),PBKDF2_ITERATIONS).bits_of();
        SymmetricKey mKey3 = kdf3->derive_key(32, mMaster3, "salt1");
        InitializationVector mIV3 = kdf3->derive_key(16, mMaster3, "salt2");

        string inFilename3 = encrypted2.toStdString();
        string outFilename3 = Destination.toStdString();
        std::ifstream inFile3(inFilename3.c_str());
        std::ofstream outFile3(outFilename3.c_str());

qDebug() << "serpent";
        Pipe pipe3(get_cipher("Serpent/CBC/PKCS7", mKey3, mIV3,ENCRYPTION),new DataSink_Stream(outFile3));
                outFile3.write((const char*)mSalt3.begin(), mSalt3.size());
        pipe3.start_msg();
        inFile3 >> pipe3;
        pipe3.end_msg();


        outFile3.flush();
        outFile3.close();
        inFile3.close();


        msgBox.setText("Success!");
        msgBox.setInformativeText("File successfully encrypted!");
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.setDefaultButton(QMessageBox::Ok);
        msgBox.exec();


e.remove(); t.remove();


        return true;
    }
    catch(...)
    {
        return false;
    }
}