function signNewCert() { if (!$GLOBALS['isCA']) { return false; } else { $CAPrivKey = new Crypt_RSA(); $CAPrivKey->loadKey($GLOBALS['CAPrivKeyStr']); $CAx509 = new File_X509(); $CAx509->loadX509($GLOBALS['CAPubX509']); //认证证书 $privKey = new Crypt_RSA(); $keyArray = $CAPrivKey->createKey($GLOBALS['RSALength']); $privKey->loadKey($keyArray['privatekey']); $pubKey = new Crypt_RSA(); $pubKey->loadKey($keyArray['publickey']); $pubKey->setPublicKey(); $subject = new File_X509(); $subject->setDNProp('id-at-organizationName', $GLOBALS['CAname'] . ' cert'); $subject->setPublicKey($pubKey); $issuer = new File_X509(); $issuer->setPrivateKey($CAPrivKey); $issuer->setDN($CAx509->getDN()); $x509 = new File_X509(); $result = $x509->sign($issuer, $subject); return array('privateKey' => $privKey->getPrivateKey(), 'publicX509' => $x509->saveX509($result)); } }
function decrypting($paramCryptResponse) { $generatedPrivateKey = ''; $passPhrase = ''; $currentDir = dirname(__FILE__) . DIRECTORY_SEPARATOR; $currentDirParam = $currentDir . 'params.php'; $parentDirParam = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'params.php'; if (file_exists($parentDirParam)) { include $parentDirParam; } else { if (file_exists($currentDirParam)) { include $currentDirParam; } } $rsa = new Crypt_RSA(); $rsa->setPassword($passPhrase); $rsa->loadKey($generatedPrivateKey); $rsa->setPassword(); $privatekey = $rsa->getPrivateKey(); $priv = $rsa->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1); require_once 'lib/bi2php/biRSA.php'; $keyDecrypt = new biRSAKeyPair('0', $priv['privateExponent']->toHex(), $priv['modulus']->toHex()); $decrypted = $keyDecrypt->biDecryptedString($paramCryptResponse); if ($decrypted === false) { return array(false, false); } $nlPos = strpos($decrypted, "\n"); $nlPos = $nlPos === false ? strlen($decrypted) : $nlPos; $password = $keyDecrypt->biDecryptedString(substr($decrypted, 0, $nlPos)); $password = strlen($password) == 0 ? "f32b309d4759446fc81de858322ed391a0c167a0" : $password; $challenge = substr($decrypted, $nlPos + 1); return array($password, $challenge); }
/** * Compute a public key identifier. * * Although key identifiers may be set to any unique value, this function * computes key identifiers from public key according to the two * recommended methods (4.2.1.2 RFC 3280). * Highly polymorphic: try to accept all possible forms of key: * - Key object * - File_X509 object with public or private key defined * - Certificate or CSR array * - File_ASN1_Element object * - PEM or DER string * * @param Mixed $key * optional * @param Integer $method * optional * @access public * @return String binary key identifier */ function computeKeyIdentifier($key = null, $method = 1) { if (is_null($key)) { $key = $this; } switch (true) { case is_string($key): break; case is_array($key) && isset($key['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']): return $this->computeKeyIdentifier($key['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'], $method); case is_array($key) && isset($key['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey']): return $this->computeKeyIdentifier($key['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey'], $method); case !is_object($key): return false; case strtolower(get_class($key)) == 'file_asn1_element': // Assume the element is a bitstring-packed key. $asn1 = new File_ASN1(); $decoded = $asn1->decodeBER($key->element); if (empty($decoded)) { return false; } $raw = $asn1->asn1map($decoded[0], array('type' => FILE_ASN1_TYPE_BIT_STRING)); if (empty($raw)) { return false; } $raw = base64_decode($raw); // If the key is private, compute identifier from its // corresponding public key. if (!class_exists('Crypt_RSA')) { include_once 'Crypt/RSA.php'; } $key = new Crypt_RSA(); if (!$key->loadKey($raw)) { return false; // Not an unencrypted RSA key. } if ($key->getPrivateKey() !== false) { // If private. return $this->computeKeyIdentifier($key, $method); } $key = $raw; // Is a public key. break; case strtolower(get_class($key)) == 'file_x509': if (isset($key->publicKey)) { return $this->computeKeyIdentifier($key->publicKey, $method); } if (isset($key->privateKey)) { return $this->computeKeyIdentifier($key->privateKey, $method); } if (isset($key->currentCert['tbsCertificate']) || isset($key->currentCert['certificationRequestInfo'])) { return $this->computeKeyIdentifier($key->currentCert, $method); } return false; default: // Should be a key object (i.e.: Crypt_RSA). $key = $key->getPublicKey(CRYPT_RSA_PUBLIC_FORMAT_PKCS1); break; } // If in PEM format, convert to binary. $key = $this->_extractBER($key); // Now we have the key string: compute its sha-1 sum. if (!class_exists('Crypt_Hash')) { include_once 'Crypt/Hash.php'; } $hash = new Crypt_Hash('sha1'); $hash = $hash->hash($key); if ($method == 2) { $hash = substr($hash, -8); $hash[0] = chr(ord($hash[0]) & 0xf | 0x40); } return $hash; }
public function testSSHPubKey() { $rsa = new Crypt_RSA(); $key = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4e' . 'CZ0FPqri0cb2JZfXJ/DgYSF6vUpwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMS' . 'GkVb1/3j+skZ6UtW+5u09lHNsj6tQ51s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZw== ' . 'phpseclib-generated-key'; $this->assertTrue($rsa->loadKey($key)); $this->assertInternalType('string', $rsa->getPublicKey()); $this->assertFalse($rsa->getPrivateKey()); }
/** * @param array $input * @param array $errors * @param array $options */ private function process_standard_options(&$input, &$errors, &$options) { if (empty($input[LaunchKey_WP_Options::OPTION_ROCKET_KEY])) { $errors[] = $this->wp_facade->__('Rocket Key is a required field', $this->language_domain); } else { $rocket_key = trim($input[LaunchKey_WP_Options::OPTION_ROCKET_KEY]); if (!is_numeric($rocket_key)) { $errors[] = $this->wp_facade->__('Rocket Key must be numeric', $this->language_domain); } elseif (strlen($rocket_key) !== 10) { $errors[] = $this->wp_facade->__('Rocket Key must be 10 digits', $this->language_domain); } else { $options[LaunchKey_WP_Options::OPTION_ROCKET_KEY] = $rocket_key; } } if (empty($input[LaunchKey_WP_Options::OPTION_SECRET_KEY]) && empty($options[LaunchKey_WP_Options::OPTION_SECRET_KEY])) { $errors[] = $this->wp_facade->__('Secret Key is a required field', $this->language_domain); } else { if (!empty($input[LaunchKey_WP_Options::OPTION_SECRET_KEY])) { $secret_key = trim($input[LaunchKey_WP_Options::OPTION_SECRET_KEY]); if (!ctype_alnum($secret_key)) { $errors[] = $this->wp_facade->__('Secret Key must be alphanumeric', $this->language_domain); } elseif (strlen($secret_key) !== 32) { $errors[] = $this->wp_facade->__('Secret Key must be 32 characters', $this->language_domain); } else { $options[LaunchKey_WP_Options::OPTION_SECRET_KEY] = $secret_key; } } } $app_display_name = isset($input[LaunchKey_WP_Options::OPTION_APP_DISPLAY_NAME]) ? trim($input[LaunchKey_WP_Options::OPTION_APP_DISPLAY_NAME]) : null; if ('LaunchKey' !== $app_display_name && LaunchKey_WP_Implementation_Type::WHITE_LABEL !== $options[LaunchKey_WP_Options::OPTION_IMPLEMENTATION_TYPE]) { $errors[] = $this->wp_facade->__('App Display Name can only be modified for White Label implementations', $this->language_domain); $options[LaunchKey_WP_Options::OPTION_APP_DISPLAY_NAME] = 'LaunchKey'; } else { $options[LaunchKey_WP_Options::OPTION_APP_DISPLAY_NAME] = $app_display_name ?: null; } if (empty($_FILES['private_key']['tmp_name']) && empty($options[LaunchKey_WP_Options::OPTION_PRIVATE_KEY]) && isset($options[LaunchKey_WP_Options::OPTION_IMPLEMENTATION_TYPE]) && LaunchKey_WP_Implementation_Type::requires_private_key($options[LaunchKey_WP_Options::OPTION_IMPLEMENTATION_TYPE])) { $errors[] = $this->wp_facade->__('Private Key is required', $this->language_domain); } else { if (!empty($_FILES['private_key']['tmp_name'])) { $private_key = @file_get_contents($_FILES['private_key']['tmp_name']); $rsa = new Crypt_RSA(); if (@$rsa->loadKey($private_key)) { if ($rsa->getPrivateKey($rsa->privateKeyFormat)) { $options[LaunchKey_WP_Options::OPTION_PRIVATE_KEY] = $private_key; } else { $errors[] = $this->wp_facade->__('The Key file provided was a valid RSA key file but did not contain a private key. Did you mistakenly supply the public key file?', $this->language_domain); } } else { $errors[] = $this->wp_facade->__('The Private Key provided was invalid', $this->language_domain); } } } }
/** * @param $dbProxyInstance * @param $options * @param $file * @param $isURL * @return array */ public function checkForFileMakerMedia($dbProxyInstance, $options, $file, $isURL) { if (strpos($file, "/fmi/xml/cnt/") === 0) { // FileMaker's container field storing an image. if (isset($options['authentication']['user'][0]) && $options['authentication']['user'][0] == 'database_native') { $passPhrase = ''; $generatedPrivateKey = ''; // avoid errors for defined in params.php. $currentDir = dirname(__FILE__) . DIRECTORY_SEPARATOR; $currentDirParam = $currentDir . 'params.php'; $parentDirParam = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'params.php'; if (file_exists($parentDirParam)) { include $parentDirParam; } else { if (file_exists($currentDirParam)) { include $currentDirParam; } } $rsa = new Crypt_RSA(); $rsa->setPassword($passPhrase); $rsa->loadKey($generatedPrivateKey); $rsa->setPassword(); $privatekey = $rsa->getPrivateKey(); $priv = $rsa->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1); require_once 'lib/bi2php/biRSA.php'; $keyDecrypt = new biRSAKeyPair('0', $priv['privateExponent']->toHex(), $priv['modulus']->toHex()); $cookieNameUser = '******'; $cookieNamePassword = '******'; $credential = isset($_COOKIE[$cookieNameUser]) ? urlencode($_COOKIE[$cookieNameUser]) : ''; if (isset($_COOKIE[$cookieNamePassword])) { $credential .= ':' . urlencode($keyDecrypt->biDecryptedString($_COOKIE[$cookieNamePassword])); } $urlHost = $dbProxyInstance->dbSettings->getDbSpecProtocol() . '://' . $credential . '@' . $dbProxyInstance->dbSettings->getDbSpecServer() . ':' . $dbProxyInstance->dbSettings->getDbSpecPort(); } else { $urlHost = $dbProxyInstance->dbSettings->getDbSpecProtocol() . "://" . urlencode($dbProxyInstance->dbSettings->getDbSpecUser()) . ":" . urlencode($dbProxyInstance->dbSettings->getDbSpecPassword()) . "@" . $dbProxyInstance->dbSettings->getDbSpecServer() . ":" . $dbProxyInstance->dbSettings->getDbSpecPort(); } $file = $urlHost . str_replace(" ", "%20", $file); foreach ($_GET as $key => $value) { if ($key !== 'media' && $key !== 'attach') { $file .= "&" . urlencode($key) . "=" . urlencode($value); } } $isURL = true; return array($file, $isURL); } return array($file, $isURL); }
$subject->setDNProp('id-at-organizationName', 'phpseclib demo CA'); $subject->setPublicKey($pubKey); $issuer = new File_X509(); $issuer->setPrivateKey($CAPrivKey); $issuer->setDN($CASubject = $subject->getDN()); $x509 = new File_X509(); $x509->makeCA(); $result = $x509->sign($issuer, $subject); echo "the CA cert to be imported into the browser is as follows:\r\n\r\n"; echo $x509->saveX509($result); echo "\r\n\r\n"; // create private key / x.509 cert for stunnel / website $privKey = new Crypt_RSA(); extract($privKey->createKey()); $privKey->loadKey($privatekey); $pubKey = new Crypt_RSA(); $pubKey->loadKey($publickey); $pubKey->setPublicKey(); $subject = new File_X509(); $subject->setDNProp('id-at-organizationName', 'phpseclib demo cert'); $subject->setPublicKey($pubKey); $issuer = new File_X509(); $issuer->setPrivateKey($CAPrivKey); $issuer->setDN($CASubject); $x509 = new File_X509(); $result = $x509->sign($issuer, $subject); echo "the stunnel.pem contents are as follows:\r\n\r\n"; echo $privKey->getPrivateKey(); echo "\r\n"; echo $x509->saveX509($result); echo "\r\n";
public function testDecryptJSGenerated() { $generatedKey = <<<EOL -----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAxH7++yiHJUHEDU3wMw+FDfrlgOHNP+yiCFmYQPI0G7oj5uTy tPMv3YVrEtb2Y62452C6WZcLSwOBqWlLUGfH0NJx35aaZG2CsUheNJEH+WEIFyel mJmWDmwfZ6DnO+nsICylGWryDfgF7n4854mxa/SfI5bYAJD6x2D3o/NDwanlsbiU B/ICKQmhZXvqNRRWdIEALasdLsDQ15MCfBTG1vKZqB9hiCFnZQEvrUKfWLdp6Uqa j15QdEvTFopramsTkQHlOy/CnQDD7Qng8Qzqm7Ycq3Xz2R/nq5k/GeAnQdxKzW1j QhktWfYrFQtxhyKcPXa/bchNkzctp3a/QRN2WwIDAQABAoIBAFvXoAZ0ovZfDuvJ CgRTtLUcGDltUSoXyIRunCN/EawEDNPXHzpEkJLR0YI0x2U/xbUgGPnXB4hAU1KD zJgAafzI4EDJe9CE/xkt4hpfz4JYQBfSiCwTXXfQQb2GD46Jf7xqIaEHw6uTyfH3 PzBZw3vaEqfn0X4yRYT7ZcRT58+UcAQJqQDU/6ZwNckewzhWzh/27LfstV+nJe5u GSmRdb2H3x9ISKb+EMysM0n+YrNKC9giObCRm7EbIOE5iJvZnA0SiBP/y90anhsS gHXaN4/cL5/U/ld9Nuk+MOH6R0qoVuGegDjdqHC+fCMUYbMvWKbnZiHU0/PnFfnu SKxkmgECgYEA4kQDLLEq9ebk1nS402AWx0XNlJHmVR/PFUbVTOT1xMWFhZA4XMnX KkMmeYIUMDJJcLbTBUYFeoygOM8TA5BSATxHGt9xrO2dl75HWVYP7Ncedc4iSj6P dM4EsnFHKCgL2LqEuaQnMIDTZKo0WnlLphChJ3MzXwVzK5lXAiKHnaECgYEA3lF6 /o0mYjWTV0PDDYvUp6mtf2h5/V/wSDA7I4IJ9BpnsOIFCdShn8rDYN9qxJS0t3US 8kNNXgFrq2zjCDMibr1xALnyXnPlc86c2+kfgv+7Biu2foJ3MI4cL9umn/y76ENE 6VaO9bUs1HHKA0SFXNEr3ZFjm+kzx3qZZh1MensCgYBn99yFkrss1vXb3TJ4XjTZ SCfY1tnBz6X2HuAwPxz3V9OstcJQUKa/0q9BMhZYtyKr2jZIvA4Ua73LnMsd3hjw XGRH4th3H5BEg7iBQlx69bYXZ6q19t0wTOI3pHmP6CbZZYtLSjR/wxJftR3tXML4 AbgrSnIWfYiYRhOG9ZrfQQKBgFkxTWwUywJ5xhwrlnS31eBSRcYo71BFDkyX9RIA 2OdzNIiVlTnlcdZ+7bXOzLIDiyFTOf+yGrcNUNocvFUM1tKg9FY7Q867JqI4kVv1 Amx3FtyZ6wSEaTc0vIBC2m2zYtwDKQGIdaCESHEPGeIHuo2LadLhwpnJjLmKKUL7 nDRDAoGADIHzuzFTYYgG4heLd2yXGv5+MDX+NmVzTr1j5dVOfzpiBJBjCN8Q9x3v v9nNeZFIhPbhCTjCdY/NlcIHOZqUQulTu1DpDZ7zFO1Fs4aEDnBvp9i8yJquxhOQ dBazzmZ3S/t2b6NtqClmn/1BgjgnKYURBn888UzbX6lqCNG3/mI= -----END RSA PRIVATE KEY----- EOL; $enc = '8c87f3e5ef1021a764e80b92b3cf168130b8cb5c5b72016449bfb812da1718cc' . 'ea125dec512a9c91bfc336f35ea1804aafb2ef6b55c715a2fca2c90491d270bd' . '9a857bee7734bfef3252afac67cb3a6c8dcc9168164a44a9c8f31001289077ef' . '3e493d4581cdb94c7812140d1ebca802636cf16cdc5fe48128f758094ebe64fe' . '4b7fb1fb814c8502e1c52fcd9cbc3431a7fc8f3f8dda146eef15b4d14192f444' . '6b9cff5bd8c3f2c8ba90b00ab93263182ad3ed7ad0d460cc02529826c6048091' . '1c712d6e212ced1a7f5fc18a1574fdceb101f28d13cd106e8d04a24de9ab3570' . '77fee33e168b584a1cbf6ea27de9e88a89e1616b18897cd7288d2a02c62434a7'; $rsa = new Crypt_RSA(); $rsa->loadKey($generatedKey); $keyComp = $rsa->_parseKey($rsa->getPrivateKey(), CRYPT_RSA_PRIVATE_FORMAT_PKCS1); $keyDecrypt = new biRSAKeyPair('0', $keyComp['privateExponent']->toHex(), $keyComp['modulus']->toHex()); $decrypted = $keyDecrypt->biDecryptedString($enc); $this->assertEquals("1234OhmyGOD#", $decrypted, "Decrypt from JavaScript encripted date."); }
$Request_Albert .= ' <key>kCTPostponementInfoPRLName</key>' . "\n"; $Request_Albert .= ' <integer>' . $kCTPostponementInfoPRLName . '</integer>' . "\n"; } $Request_Albert .= '</dict>' . "\n"; $Request_Albert .= '</plist>'; // Fetch iPhoneActivation Certificate's Private Key. //$AccountCertificate = file_get_contents ( "certs" . DS . "iPhoneActivation.pem" ); //$iPhoneActivationVect = openssl_pkey_get_details ( openssl_pkey_get_public ( $AccountCertificate ) ); //$iPhoneActivationPublicKey = $iPhoneActivationVect [ 'key' ]; //$AccountTokenCertificate = base64_encode ( $AccountCertificate ); //$iPhoneActivationPublicKeyPrivateKey = openssl_pkey_get_private ( file_get_contents ( "certs" . DS . "iPhoneActivation_private.key" ) ); $iPhoneDeviceCA_private = file_get_contents($FairplayFile); $CA_Key = new Crypt_RSA(); $CA_Key->loadKey($iPhoneDeviceCA_private); $iPhoneDeviceCA = file_get_contents($FairplayFile); $haha = $CA_Key->getPrivateKey($iPhoneDeviceCA_private); print_r($haha); $CA_Certificate = new File_X509(); //$haha = $CA_Certificate->setPrivateKey ( $CA_Key ); //$haha = $CA_Certificate->getPrivateKey ( $CA_Key ); //print_r($haha); //$CA_Certificate->loadX509 ( $iPhoneDeviceCA ); //$test = $CA_Certificate->loadX509($CA_Certificate->saveX509($CA_Certificate->sign($CA_Certificate, $Request_Albert))); //$Certificate = $CA_Certificate->saveX509($test); //echo $test; // Sign the AccountTocken. //$StringSignature = ""; //openssl_sign ( $Request_Albert, $StringSignature, $iPhoneActivationPublicKeyPrivateKey ); //$FairPlaySignature = base64_encode ( $StringSignature ); // activation-info-base64 decoded version template , activation-info & certify-me-info template. $Request_Info = '<dict>' . "\n";
/** * @param $options * @param null $access * @param bool $bypassAuth */ function processingRequest($options, $access = null, $bypassAuth = false) { $this->logger->setDebugMessage("[processingRequest]", 2); $this->outputOfPrcessing = ''; $generatedPrivateKey = ''; $passPhrase = ''; $currentDir = dirname(__FILE__) . DIRECTORY_SEPARATOR; $currentDirParam = $currentDir . 'params.php'; $parentDirParam = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'params.php'; if (file_exists($parentDirParam)) { include $parentDirParam; } else { if (file_exists($currentDirParam)) { include $currentDirParam; } } $messageClass = null; if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) { $clientLangArray = explode(',', $_SERVER["HTTP_ACCEPT_LANGUAGE"]); foreach ($clientLangArray as $oneLanguage) { $langCountry = explode(';', $oneLanguage); if (strlen($langCountry[0]) > 0) { $clientLang = explode('-', $langCountry[0]); $messageClass = "MessageStrings_{$clientLang['0']}"; if (file_exists("{$currentDir}{$messageClass}.php")) { $messageClass = new $messageClass(); break; } } $messageClass = null; } } if ($messageClass == null) { $messageClass = new MessageStrings(); } $tableInfo = $this->dbSettings->getDataSourceTargetArray(); $access = is_null($access) ? $_POST['access'] : $access; $clientId = isset($_POST['clientid']) ? $_POST['clientid'] : (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : "Non-browser-client"); $this->paramAuthUser = isset($_POST['authuser']) ? $_POST['authuser'] : ""; $paramResponse = isset($_POST['response']) ? $_POST['response'] : ""; $this->dbSettings->setRequireAuthentication(false); $this->dbSettings->setRequireAuthorization(false); $this->dbSettings->setDBNative(false); $keywordAuth = $access == "select" ? "load" : $access; if (isset($options['authentication']) || $access == 'challenge' || $access == 'changepassword' || isset($tableInfo['authentication']) && (isset($tableInfo['authentication']['all']) || isset($tableInfo['authentication'][$keywordAuth]))) { $this->dbSettings->setRequireAuthorization(true); $this->dbSettings->setDBNative(false); if (isset($options['authentication']['user']) && $options['authentication']['user'][0] == 'database_native') { $this->dbSettings->setDBNative(true); } } // $this->logger->setDebugMessage("dbNative={$this->dbSettings->isDBNative()}", 2); // $this->logger->setDebugMessage("", 2); if (!$bypassAuth && $this->dbSettings->getRequireAuthorization()) { // Authentication required if (strlen($this->paramAuthUser) == 0 || strlen($paramResponse) == 0) { // No username or password $access = "do nothing"; $this->dbSettings->setRequireAuthentication(true); } // User and Password are suppried but... if ($access != 'challenge') { // Not accessing getting a challenge. if ($this->dbSettings->isDBNative()) { $rsa = new Crypt_RSA(); $rsa->setPassword($passPhrase); $rsa->loadKey($generatedPrivateKey); $rsa->setPassword(); $privatekey = $rsa->getPrivateKey(); $priv = $rsa->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1); require_once 'bi2php/biRSA.php'; $keyDecrypt = new biRSAKeyPair('0', $priv['privateExponent']->toHex(), $priv['modulus']->toHex()); $decrypted = $keyDecrypt->biDecryptedString($paramResponse); // $this->logger->setDebugMessage("decrypted={$decrypted}", 2); if ($decrypted !== false) { $nlPos = strpos($decrypted, "\n"); $nlPos = $nlPos === false ? strlen($decrypted) : $nlPos; $password = $keyDecrypt->biDecryptedString(substr($decrypted, 0, $nlPos)); $password = strlen($password) == 0 ? "f32b309d4759446fc81de858322ed391a0c167a0" : $password; $challenge = substr($decrypted, $nlPos + 1); // $this->logger->setDebugMessage("password={$password}", 2); // $this->logger->setDebugMessage("paramAuthUser={$this->paramAuthUser}", 2); if (!$this->checkChallenge($challenge, $clientId)) { $access = "do nothing"; $this->dbSettings->setRequireAuthentication(true); } else { $this->dbSettings->setUserAndPasswordForAccess($this->paramAuthUser, $password); $this->logger->setDebugMessage("[checkChallenge] returns true.", 2); } } else { $this->logger->setDebugMessage("Can't decrypt."); $access = "do nothing"; $this->dbSettings->setRequireAuthentication(true); } } else { $noAuthorization = true; $authorizedGroups = $this->dbClass->getAuthorizedGroups($access); $authorizedUsers = $this->dbClass->getAuthorizedUsers($access); $this->logger->setDebugMessage("authorizedUsers=" . var_export($authorizedUsers, true) . "/authorizedGroups=" . var_export($authorizedGroups, true), 2); if (count($authorizedUsers) == 0 && count($authorizedGroups) == 0) { $noAuthorization = false; } else { $signedUser = $this->dbClass->authSupportUnifyUsernameAndEmail($this->dbSettings->getCurrentUser()); if (in_array($signedUser, $authorizedUsers)) { $noAuthorization = false; } else { if (count($authorizedGroups) > 0) { $belongGroups = $this->dbClass->authSupportGetGroupsOfUser($signedUser); $this->logger->setDebugMessage($signedUser . "=belongGroups=" . var_export($belongGroups, true), 2); if (count(array_intersect($belongGroups, $authorizedGroups)) != 0) { $noAuthorization = false; } } } } if ($noAuthorization) { $this->logger->setDebugMessage("Authorization doesn't meet the settings."); $access = "do nothing"; $this->dbSettings->setRequireAuthentication(true); } $signedUser = $this->dbClass->authSupportUnifyUsernameAndEmail($this->paramAuthUser); if (!$this->checkAuthorization($signedUser, $paramResponse, $clientId)) { $this->logger->setDebugMessage("Authentication doesn't meet valid.{$signedUser}/{$paramResponse}/{$clientId}"); // Not Authenticated! $access = "do nothing"; $this->dbSettings->setRequireAuthentication(true); } } } } // $this->logger->setDebugMessage("requireAuthentication={$this->dbSettings->getRequireAuthentication()}", 2); // $this->logger->setDebugMessage("requireAuthorization={$this->dbSettings->getRequireAuthorization()}", 2); // $this->logger->setDebugMessage("access={$access}, target={$this->dbSettings->getTargetName()}", 2); // Come here access=challenge or authenticated access switch ($access) { case 'describe': $result = $this->dbClass->getSchema($this->dbSettings->getTargetName()); $this->outputOfPrcessing = 'dbresult=' . arrayToJS($result, '') . ';' . "resultCount=0;"; break; case 'select': $result = $this->getFromDB($this->dbSettings->getTargetName()); if (isset($tableInfo['protect-reading']) && is_array($tableInfo['protect-reading'])) { $recordCount = count($result); for ($index = 0; $index < $recordCount; $index++) { foreach ($result[$index] as $field => $value) { if (in_array($field, $tableInfo['protect-reading'])) { $result[$index][$field] = "[protected]"; } } } } $this->outputOfPrcessing = 'dbresult=' . arrayToJS($result, '') . ';' . "resultCount='{$this->countQueryResult($this->dbSettings->getTargetName())}';"; break; case 'update': if (isset($tableInfo['protect-writing']) && is_array($tableInfo['protect-writing'])) { $fieldArray = array(); $valueArray = array(); $counter = 0; $fieldValues = $this->dbSettings->getValue(); foreach ($this->dbSettings->getFieldsRequired() as $field) { if (!in_array($field, $tableInfo['protect-writing'])) { $fieldArray[] = $field; $valueArray[] = $fieldValues[$counter]; } $counter++; } $this->dbSettings->setTargetFields($fieldArray); $this->dbSettings->setValue($valueArray); } $this->setToDB($this->dbSettings->getTargetName()); break; case 'new': $result = $this->newToDB($this->dbSettings->getTargetName(), $bypassAuth); $this->outputOfPrcessing = "newRecordKeyValue='{$result}';"; break; case 'delete': $this->deleteFromDB($this->dbSettings->getTargetName()); break; case 'challenge': break; case 'changepassword': if (isset($_POST['newpass'])) { $changeResult = $this->changePassword($this->paramAuthUser, $_POST['newpass']); $this->outputOfPrcessing = "changePasswordResult=" . ($changeResult ? "true;" : "false;"); } else { $this->outputOfPrcessing = "changePasswordResult=false;"; } break; } // $this->logger->setDebugMessage("requireAuthentication={$this->dbSettings->getRequireAuthentication()}", 2); // $this->logger->setDebugMessage("requireAuthorization={$this->dbSettings->getRequireAuthorization()}", 2); if ($this->logger->getDebugLevel() !== false) { $fInfo = $this->getFieldInfo($this->dbSettings->getTargetName()); if ($fInfo != null) { foreach ($this->dbSettings->getFieldsRequired() as $fieldName) { if (!in_array($fieldName, $fInfo)) { $this->logger->setErrorMessage($messageClass->getMessageAs(1033, array($fieldName))); } } } } }