int main(int argc, char ** argv) { // Global errno reset to properly parse errors from fopen() function call errno = 0; // User specified passphrase char password[BUFSIZ]; // Length of the password int length = 0; // Randomly generated key char key[BUFSIZ]; // Bitmask used to encrypt file char mask[BUFSIZ]; // Set to user-specified file FILE * file = 0; // Check if a file is specified if(--argc != 1) { (void)fprintf(stderr, USAGE); return EXIT_FAILURE; } file = fopen(argv[1], READ_MODE); // Check if file is valid if(file == NULL) { if(errno == EACCES) { // User does not have permission to read/write file, print error (void)fprintf(stderr, NO_ACCESS); return EXIT_FAILURE; } else { // File itself is invalid, print error (void)fprintf(stderr, FILE_INVALID); return EXIT_FAILURE; } } else { (void)printf(PASS_PROMPT); (void)scanf("%s", password); // Check if password is at least 8 characters long if(!parsePassword(password, &length)) { (void)fprintf(stderr, PASS_SHORT); return EXIT_FAILURE; } // Randomly generate the key based on password length (void)generateKey(length, key); (void)generateMask(key, password, mask, length); } return EXIT_SUCCESS; }
inline bool getAgileSecretKey(std::string& secretKey, const EncryptionInfo& info, const std::string& pass) { const CipherParam& keyData = info.keyData; const CipherParam& encryptedKey = info.encryptedKey; const std::string& iv = encryptedKey.saltValue; const std::string pwHash = hashPassword(encryptedKey.hashName, iv, pass, info.spinCount); const std::string skey1 = generateKey(encryptedKey, pwHash, ms::blkKey_VerifierHashInput); const std::string skey2 = generateKey(encryptedKey, pwHash, ms::blkKey_encryptedVerifierHashValue); const std::string verifierHashInput = cipher(encryptedKey.cipherName, info.encryptedVerifierHashInput, skey1, iv, cybozu::crypto::Cipher::Decoding); const std::string hashedVerifier = cybozu::crypto::Hash::digest(encryptedKey.hashName, verifierHashInput); const std::string verifierHash = cipher(encryptedKey.cipherName, info.encryptedVerifierHashValue, skey2, iv, cybozu::crypto::Cipher::Decoding).substr(0, hashedVerifier.size()); if (hashedVerifier != verifierHash) { return false; } const std::string skey3 = generateKey(encryptedKey, pwHash, ms::blkKey_encryptedKeyValue); secretKey = cipher(encryptedKey.cipherName, info.encryptedKeyValue, skey3, iv, cybozu::crypto::Cipher::Decoding); if (isDebug()) { printf("salt = "); dump(keyData.saltValue, false); printf("secretKey = "); dump(secretKey, false); } return true; }
QVector<QString> & SitecomKeygen::getKeys() { QString mac = getMacAddress(); if ( mac.length() < 12 ) { throw ERROR; } generateKey(mac); QString shortMac = mac.left(11); int lastChar = mac.right(1).toInt(0, 16); lastChar = (lastChar + 1) % 0x10; generateKey(shortMac + QString::number(lastChar, 16).toUpper()); lastChar = (lastChar + 1) % 0x10; generateKey(shortMac + QString::number(lastChar, 16).toUpper()); return results; }
QString StubKeyring::getPassword(QString service, QString username) { QString key = generateKey(service, username); if (!m_settings.contains(key)) return QString(); return unscramble64(m_settings.value(key).toString()); }
void WalletSerializer::loadCurrentVersion(Common::IInputStream& source, const std::string& password) { CryptoNote::CryptoContext cryptoContext; bool details = false; bool cache = false; loadIv(source, cryptoContext.iv); generateKey(password, cryptoContext.key); loadKeys(source, cryptoContext); checkKeys(); loadWallets(source, cryptoContext); subscribeWallets(); loadFlags(details, cache, source, cryptoContext); if (details) { loadTransactions(source, cryptoContext); loadTransfers(source, cryptoContext); } if (cache) { loadBalances(source, cryptoContext); loadTransfersSynchronizer(source, cryptoContext); loadSpentOutputs(source, cryptoContext); loadUnlockTransactionsJobs(source, cryptoContext); loadChange(source, cryptoContext); } if (details && cache) { updateTransactionsBaseStatus(); } }
ECDSAKeyPair::ECDSAKeyPair(ByteArray& derEncoded) throw (AsymmetricKeyException) { this->key = NULL; this->engine = NULL; EC_GROUP * group = createGroup(derEncoded); generateKey(group); EC_GROUP_free(group); }
ECDSAKeyPair::ECDSAKeyPair(const EllipticCurve & curve) throw (AsymmetricKeyException) { this->key = NULL; this->engine = NULL; EC_GROUP * group = createGroup(curve); generateKey(group); EC_GROUP_free(group); }
int main(int argc, char **argv) { Q_UNUSED(argc); Q_UNUSED(argv); basicCheck(); QHash<QString, int> hash; Trie<int> t; while (hash.count() < 500) { qDebug() << hash.count(); QStringList key = generateKey(); int value = qrand() % 50000; hash[key.join(QLatin1String(","))] = value; t.insert(key, value); QHashIterator<QString, int> i(hash); while (i.hasNext()) { i.next(); if (t.find(i.key().split(QLatin1Char(','))).count() == 0) qDebug() << i.key(); Q_ASSERT(t.find(i.key().split(QLatin1Char(','))).count() > 0); if (qrand() % 500 == 0) { t.remove(i.key().split(QLatin1Char(',')), i.value()); hash.remove(i.key()); } //cout << i.key() << ": " << i.value() << endl; } } return 0; }
std::string generateIv(const std::string& salt, const std::string& blockKey) { if (blockKey.empty()) { return salt.substr(0, 16); } return generateKey(salt, blockKey); }
void ConnectionBOSHPrivate::sendHeader(bool first) { streamInitiation = first; writer.writeEmptyElement(QLatin1String("body")); writer.writeAttribute(QLatin1String("rid"), QString::number(rid++)); if (first) { writer.writeAttribute(QLatin1String("from"), jid.bare()); writer.writeAttribute(QLatin1String("route"), QLatin1String("xmpp:") + jid.domain() + QLatin1String(":5222")); writer.writeAttribute(QLatin1String("secure"), QLatin1String("true")); writer.writeAttribute(QLatin1String("hold"), QLatin1String("2")); writer.writeAttribute(QLatin1String("ver"), QLatin1String("1.8")); writer.writeAttribute(QLatin1String("xmpp:version"), QLatin1String("1.0")); writer.writeAttribute(QLatin1String("xml:lang"), QLatin1String("en")); } else { writer.writeAttribute(QLatin1String("xmpp:restart"), QLatin1String("true")); writer.writeAttribute(QLatin1String("key"), QLatin1String(nextKey())); writer.writeAttribute(QLatin1String("sid"), sessionId); } writer.writeAttribute(QLatin1String("newkey"), QLatin1String(generateKey())); writer.writeAttribute(QLatin1String("to"), jid.domain()); writer.writeDefaultNamespace(QLatin1String("http://jabber.org/protocol/httpbind")); writer.writeAttribute(QLatin1String("xmlns:xmpp"), QLatin1String("urn:xmpp:xbosh")); writer.writeCharacters(QLatin1String("")); send(false, true); }
std::string GSSContextCache::store ( GSSContext& data, std::string inKey ) { /* Variables */ std::string key; /* Error checking */ /* Setup */ /* Main */ // Generate a key if ( inKey.length() > 0 ) { key = inKey; } else if ( !generateKey(key) ) { // Key generation failed. Eeek! throw std::runtime_error("Could not generate random data for an ID"); } // Store the key/value pair in the map // Store the key in the context for convenience contexts[key] = data; /* Cleanup */ /* Return */ // Return the key for future reference return(key); }
QTextFormat::QTextFormat( const QStyleSheetItem *style ) : fm( QFontMetrics( fn ) ), linkColor( TRUE ), logicalFontSize( 3 ), stdPointSize( qApp->font().pointSize() ), painter( 0 ), different( NoFlags ) { ref = 0; this->style = style->name(); missp = FALSE; ha = AlignNormal; collection = 0; fn = QFont( style->fontFamily(), style->fontSize(), style->fontWeight(), style->fontItalic() ); fn.setUnderline( style->fontUnderline() ); col = style->color(); fm = QFontMetrics( fn ); leftBearing = fm.minLeftBearing(); rightBearing = fm.minRightBearing(); hei = fm.height(); asc = fm.ascent(); dsc = fm.descent(); missp = FALSE; ha = AlignNormal; memset( widths, 0, 256 ); generateKey(); addRef(); updateStyleFlags(); }
void WalletSerializer::loadWalletV1(Common::IInputStream& source, const std::string& password) { CryptoNote::CryptoContext cryptoContext; CryptoNote::BinaryInputStreamSerializer encrypted(source); encrypted(cryptoContext.iv, "iv"); generateKey(password, cryptoContext.key); std::string cipher; encrypted(cipher, "data"); std::string plain = decrypt(cipher, cryptoContext); MemoryInputStream decryptedStream(plain.data(), plain.size()); CryptoNote::BinaryInputStreamSerializer serializer(decryptedStream); loadWalletV1Keys(serializer); checkKeys(); subscribeWallets(); bool detailsSaved; serializer(detailsSaved, "has_details"); if (detailsSaved) { loadWalletV1Details(serializer); } }
game::Symbol_Core* Operator::toByteCode(game::Symbol_Core* _operand0, game::Symbol_Core* _operand1, game::ByteCodeStack* _stack) { auto it = overloads.find(generateKey(_operand0, _operand1)); if (it == overloads.end()) { it = overloads.find(generateKey(_operand1, _operand0)); if (it != overloads.end()) { std::swap(_operand0, _operand1); } else return nullptr; } return (*it).second(_operand0, _operand1, _stack); }
QTextFormat::QTextFormat( const QStyleSheetItem *style ) : fm( QFontMetrics( fn ) ), linkColor( TRUE ), logicalFontSize( 3 ), stdSize( qApp->font().pointSize() ) { ref = 0; usePixelSizes = FALSE; if ( stdSize == -1 ) { stdSize = qApp->font().pixelSize(); usePixelSizes = TRUE; } missp = FALSE; ha = AlignNormal; collection = 0; fn = QFont( style->fontFamily(), style->fontSize(), style->fontWeight(), style->fontItalic() ); fn.setUnderline( style->fontUnderline() ); fn.setStrikeOut( style->fontStrikeOut() ); col = style->color(); fm = QFontMetrics( fn ); leftBearing = fm.minLeftBearing(); rightBearing = fm.minRightBearing(); hei = fm.lineSpacing(); asc = fm.ascent() + (fm.leading()+1)/2; dsc = fm.descent(); missp = FALSE; ha = AlignNormal; memset( widths, 0, 256 ); generateKey(); addRef(); }
//------------------------------------------------------------------------------------- KBEKey::KBEKey(const std::string& pubkeyname, const std::string& prikeyname): KBE_RSA() { if(pubkeyname.size() > 0 || prikeyname.size() > 0) { KBE_ASSERT(pubkeyname.size() > 0); if(g_componentType != CLIENT_TYPE) { KBE_ASSERT(prikeyname.size() > 0); bool key1 = loadPrivate(prikeyname); bool key2 = loadPublic(pubkeyname); KBE_ASSERT(key1 == key2); if(!key1 && !key2) { bool ret = generateKey(pubkeyname, prikeyname); KBE_ASSERT(ret); key1 = loadPrivate(prikeyname); key2 = loadPublic(pubkeyname); KBE_ASSERT(key1 && key2); } } else { bool key = loadPublic(pubkeyname); KBE_ASSERT(key); } } }
jstring Java_com_abc_util_JniHelp_aesDecrypt(JNIEnv *env, jobject obj, jstring s, jstring k) { //将需要解密的字符串转化为const char*类型 if (s == NULL || k == NULL){ LOGE("***aesDecrypt input s = null or k = null"); return NULL; } const char* ciphter_str = env->GetStringUTFChars(s, 0); //密钥字符串转化成char* const char* key = env->GetStringUTFChars(k, 0); unsigned char deb_key[KEY_LEN+1] =""; generateKey(env,(unsigned char*)key,deb_key); unsigned char plaint_str[CBUFF_LEN]; memset((char*) plaint_str, 0, sizeof(plaint_str)); int cipher_len = strlen(ciphter_str)/2; LOGD("****cipher_len=%d",cipher_len); //将加密后的字符串,16进制转换成unsigned char* char tempStr[(cipher_len+1)*2]; memset(tempStr,0x00,sizeof(tempStr)); strcpy(tempStr,ciphter_str); //LOGD("****tempStr=%s",tempStr); char data[cipher_len+1]; memset(data,0x00,sizeof(data)); int i=0,j=0; char tmph,tmpl; for (i=0;i<sizeof(tempStr);i+=2){ tmph = ASCI_16(tempStr[i])<<4; tmpl = ASCI_16(tempStr[i+1]); //LOGD("**tmpstr=0x%x+0x%x",tmph,tmpl); data[j] = tmph+tmpl; //LOGD("****data=0x%x",data[j]); j++; } //LOGD("****data=0x%x,0x%x,0x%x,0x%x",data[0],data[1],data[2],data[3]); unsigned char dst[CBUFF_LEN]; int plaint_len; //LOGD("--1--- dst=%x,%x,%x,%x",dst[0],dst[1],dst[2],dst[3]); plaint_len = aesdecrypt((unsigned char*)data,cipher_len,deb_key,dst); //LOGD("--2--- dst=%s",dst); LOGD("****plaint_len=%d",plaint_len); char retStr[plaint_len+1]; memset(retStr,0x00,sizeof(retStr)); strcpy(retStr,(char *)dst); env->ReleaseStringUTFChars(s,ciphter_str); env->ReleaseStringUTFChars(k,key); return env->NewStringUTF(retStr); //通过JNI提供的转化方法将char*转化为jstring作为结果返回 }
ECDSAKeyPair::ECDSAKeyPair(std::string& encoded) throw (AsymmetricKeyException) { this->key = NULL; this->engine = NULL; ByteArray derEncoded = Base64::decode(encoded); EC_GROUP * group = createGroup(derEncoded); generateKey(group); EC_GROUP_free(group); }
extern "C" ppk_error removeEntry(const ppk_entry* entry, unsigned int flags) { QString generatedKey; if (generateKey(entry, generatedKey) == PPK_FALSE) return PPK_UNKNOWN_ENTRY_TYPE; return removePassword(generatedKey, flags); }
extern "C" ppk_boolean entryExists(const ppk_entry* entry, unsigned int flags) { QString generatedKey; if (generateKey(entry, generatedKey) == PPK_FALSE) return PPK_FALSE; return passwordExists(generatedKey, flags)==PPK_OK?PPK_TRUE:PPK_FALSE; }
int main() { accept(); generateKey(); encryption(); decryption(); getch(); return 0; }
JSValue JSSubtleCrypto::generateKey(ExecState* exec) { if (exec->argumentCount() < 1) return exec->vm().throwException(exec, createNotEnoughArgumentsError(exec)); auto algorithm = createAlgorithmFromJSValue(exec, exec->uncheckedArgument(0)); if (!algorithm) { ASSERT(exec->hadException()); return jsUndefined(); } auto parameters = JSCryptoAlgorithmDictionary::createParametersForGenerateKey(exec, algorithm->identifier(), exec->uncheckedArgument(0)); if (!parameters) { ASSERT(exec->hadException()); return jsUndefined(); } bool extractable = false; if (exec->argumentCount() >= 2) { extractable = exec->uncheckedArgument(1).toBoolean(exec); if (exec->hadException()) return jsUndefined(); } CryptoKeyUsage keyUsages = 0; if (exec->argumentCount() >= 3) { if (!cryptoKeyUsagesFromJSValue(exec, exec->argument(2), keyUsages)) { ASSERT(exec->hadException()); return jsUndefined(); } } JSPromiseDeferred* promiseDeferred = JSPromiseDeferred::create(exec, globalObject()); DeferredWrapper wrapper(exec, globalObject(), promiseDeferred); auto successCallback = [wrapper](CryptoKey* key, CryptoKeyPair* keyPair) mutable { ASSERT(key || keyPair); ASSERT(!key || !keyPair); if (key) wrapper.resolve(key); else wrapper.resolve(keyPair); }; auto failureCallback = [wrapper]() mutable { wrapper.reject(nullptr); }; ExceptionCode ec = 0; algorithm->generateKey(*parameters, extractable, keyUsages, WTF::move(successCallback), WTF::move(failureCallback), ec); if (ec) { setDOMException(exec, ec); return jsUndefined(); } return promiseDeferred->promise(); }
void KoPAPixmapCache::remove( const QString & key ) { QMap<QString, QList<QSize> >::iterator it( m_keySize.find( key ) ); if ( it != m_keySize.end() ) { foreach( const QSize& size, it.value() ) { QString k = generateKey( key, size ); QPixmapCache::remove( k ); } m_keySize.erase( it ); }
void QTextFormat::update() { fm = QFontMetrics( fn ); leftBearing = fm.minLeftBearing(); rightBearing = fm.minRightBearing(); hei = fm.lineSpacing(); asc = fm.ascent() + (fm.leading()+1)/2; dsc = fm.descent(); memset( widths, 0, 256 ); generateKey(); }
/*! \internal */ void QWebSocketPrivate::processStateChanged(QAbstractSocket::SocketState socketState) { Q_ASSERT(m_pSocket); Q_Q(QWebSocket); QAbstractSocket::SocketState webSocketState = this->state(); int port = 80; if (m_requestUrl.scheme() == QStringLiteral("wss")) port = 443; switch (socketState) { case QAbstractSocket::ConnectedState: if (webSocketState == QAbstractSocket::ConnectingState) { m_key = generateKey(); const QString handshake = createHandShakeRequest(m_resourceName, m_requestUrl.host() % QStringLiteral(":") % QString::number(m_requestUrl.port(port)), origin(), QString(), QString(), m_key); if (handshake.isEmpty()) { m_pSocket->abort(); Q_EMIT q->error(QAbstractSocket::ConnectionRefusedError); return; } m_pSocket->write(handshake.toLatin1()); } break; case QAbstractSocket::ClosingState: if (webSocketState == QAbstractSocket::ConnectedState) setSocketState(QAbstractSocket::ClosingState); break; case QAbstractSocket::UnconnectedState: if (webSocketState != QAbstractSocket::UnconnectedState) { setSocketState(QAbstractSocket::UnconnectedState); Q_EMIT q->disconnected(); } break; case QAbstractSocket::HostLookupState: case QAbstractSocket::ConnectingState: case QAbstractSocket::BoundState: case QAbstractSocket::ListeningState: //do nothing //to make C++ compiler happy; break; default: break; } }
JSValue JSWebKitSubtleCrypto::generateKey(ExecState& state) { VM& vm = state.vm(); auto scope = DECLARE_THROW_SCOPE(vm); if (state.argumentCount() < 1) return throwException(&state, scope, createNotEnoughArgumentsError(&state)); auto algorithm = createAlgorithmFromJSValue(state, state.uncheckedArgument(0)); ASSERT(scope.exception() || algorithm); if (!algorithm) return jsUndefined(); auto parameters = JSCryptoAlgorithmDictionary::createParametersForGenerateKey(&state, algorithm->identifier(), state.uncheckedArgument(0)); ASSERT(scope.exception() || parameters); if (!parameters) return jsUndefined(); bool extractable = false; if (state.argumentCount() >= 2) { extractable = state.uncheckedArgument(1).toBoolean(&state); RETURN_IF_EXCEPTION(scope, JSValue()); } CryptoKeyUsageBitmap keyUsages = 0; if (state.argumentCount() >= 3) { auto success = cryptoKeyUsagesFromJSValue(state, state.argument(2), keyUsages); ASSERT(scope.exception() || success); if (!success) return jsUndefined(); } RefPtr<DeferredPromise> wrapper = createDeferredPromise(state, domWindow()); auto promise = wrapper->promise(); auto successCallback = [wrapper](CryptoKey* key, CryptoKeyPair* keyPair) mutable { ASSERT(key || keyPair); ASSERT(!key || !keyPair); if (key) wrapper->resolve(key); else wrapper->resolve(keyPair); }; auto failureCallback = [wrapper]() mutable { wrapper->reject(nullptr); }; auto result = algorithm->generateKey(*parameters, extractable, keyUsages, WTFMove(successCallback), WTFMove(failureCallback), *scriptExecutionContextFromExecState(&state)); if (result.hasException()) { propagateException(state, scope, result.releaseException()); return { }; } return promise; }
void Position::init (const unsigned int board_size) { // same for all constructors squares = ((board_size*board_size)+1)/2; // count squares where towers might move value = evaluateTowers(); #ifdef USE_POSITION_KEY tower_keys.clear(); RKISS rk; turn_key[0] = rk.rand<unsigned long long>(); turn_key[1] = rk.rand<unsigned long long>(); pos_key = generateKey(); // init pos_key #endif }
void QTextFormat::update() { fm = QFontMetrics( fn ); leftBearing = fm.minLeftBearing(); rightBearing = fm.minRightBearing(); hei = fm.height(); asc = fm.ascent(); dsc = fm.descent(); memset( widths, 0, 256 ); generateKey(); updateStyleFlags(); }
extern "C" ppk_error setEntry(const ppk_entry* entry, const ppk_data* edata, unsigned int flags) { QString generatedKey; if (generateKey(entry, generatedKey) == PPK_FALSE) return PPK_UNKNOWN_ENTRY_TYPE; if (edata->type == ppk_string) return setPassword(generatedKey, edata->string, flags); else if (edata->type == ppk_blob) return setBlob(generatedKey, edata->blob.data, edata->blob.size, flags); else return PPK_UNKNOWN_ENTRY_TYPE; }
inline void DecContent(std::string& dec, const std::string& data, const CipherParam& param, const std::string& key, const std::string& salt) { const size_t blockSize = 4096; dec.reserve(data.size()); const size_t n = (data.size() + blockSize - 1) / blockSize; for (size_t i = 0; i < n; i++) { const size_t len = (i < n - 1) ? blockSize : (data.size() % blockSize); std::string blockKey(4, 0); cybozu::Set32bitAsLE(&blockKey[0], static_cast<uint32_t>(i)); const std::string iv = generateKey(param, salt, blockKey); dec.append(cipher(param.cipherName, data.c_str() + i * blockSize, len, key, iv, cybozu::crypto::Cipher::Decoding)); } }