示例#1
0
 public function __construct($publicKey = '', $privateKey = '')
 {
     $this->rsa = new RSA();
     if (!$publicKey || !$privateKey) {
         $keys = $this->rsa->createKey();
         $this->publicKey = $keys['publickey'];
         $this->privateKey = $keys['privatekey'];
         return;
     }
     $this->publicKey = $publicKey;
     $this->privateKey = $privateKey;
 }
示例#2
0
 public function onEnable()
 {
     $this->saveDefaultConfig();
     $this->saveResource("server-icon.png", false);
     $this->saveResource("steve.yml", false);
     $this->saveResource("alex.yml", false);
     $this->reloadConfig();
     $this->onlineMode = (bool) $this->getConfig()->get("online-mode");
     if ($this->onlineMode and !function_exists("mcrypt_generic_init")) {
         $this->onlineMode = false;
         $this->getLogger()->notice("no mcrypt detected, online-mode has been disabled. Try using the latest PHP binaries");
     }
     if (!$this->getConfig()->exists("motd")) {
         $this->getLogger()->warning("No motd has been set. The server description will be empty.");
         return;
     }
     if (Info::CURRENT_PROTOCOL === 84) {
         $this->translator = new Translator_84();
         $this->rsa = new RSA();
         $this->getServer()->getPluginManager()->registerEvents($this, $this);
         Achievement::add("openInventory", "Taking Inventory");
         //this for DesktopPlayer
         if ($this->onlineMode) {
             $this->getLogger()->info("Server is being started in the background");
             $this->getLogger()->info("Generating keypair");
             $this->rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
             $this->rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
             $keys = $this->rsa->createKey(1024);
             $this->privateKey = $keys["privatekey"];
             $this->publicKey = $keys["publickey"];
             $this->rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
             $this->rsa->loadKey($this->privateKey);
         }
         $this->getLogger()->info("Starting Minecraft: PC server on " . ($this->getIp() === "0.0.0.0" ? "*" : $this->getIp()) . ":" . $this->getPort() . " version " . MCInfo::VERSION);
         $disable = true;
         foreach ($this->getServer()->getNetwork()->getInterfaces() as $interface) {
             if ($interface instanceof ProtocolInterface) {
                 $disable = false;
             }
         }
         if ($disable) {
             $this->interface = new ProtocolInterface($this, $this->getServer(), $this->translator);
             $this->getServer()->getNetwork()->registerInterface($this->interface);
         }
     } else {
         $this->getLogger()->critical("Couldn't find a protocol translator for #" . Info::CURRENT_PROTOCOL . ", disabling plugin");
         $this->getPluginLoader()->disablePlugin($this);
     }
 }
示例#3
0
文件: SSH.php 项目: dzirg44/dogpro
 public static function generateKeyPair($comment = 'dogpro')
 {
     $rsa = new RSA();
     $rsa->setPublicKeyFormat(RSA::PUBLIC_FORMAT_OPENSSH);
     $rsa->setComment($comment);
     return $rsa->createKey();
 }
示例#4
0
文件: rsa.php 项目: farukuzun/core-1
 /**
  * Generate a keypair
  *
  * @return array ['privatekey' => $privateKey, 'publickey' => $publicKey]
  */
 public function createKey()
 {
     $rsa = new RSACrypt();
     $rsa->setPublicKeyFormat(RSACrypt::PUBLIC_FORMAT_OPENSSH);
     $rsa->setPassword($this->config->getSystemValue('secret', ''));
     return $rsa->createKey(self::CREATE_KEY_BITS);
 }
示例#5
0
 public function testCreateKey()
 {
     extract(RSA::createKey(512));
     $this->assertInstanceOf('\\phpseclib\\Crypt\\RSA', $privatekey);
     $this->assertInstanceOf('\\phpseclib\\Crypt\\RSA', $publickey);
     $this->assertNotEmpty("{$privatekey}");
     $this->assertNotEmpty("{$publickey}");
     return array($publickey, $privatekey);
 }
示例#6
0
 /**
  * Generate a private/public RSA key pair
  *
  * @param int $size Key size
  * @param string $passphrase Optional - password-protected private key
  *
  * @return self
  * @throws InvalidKeyException
  */
 public static function generateKeyPair($size = 2048)
 {
     if ($size < 2048) {
         throw new InvalidKeyException('Key size must be at least 2048 bits.');
     }
     $rsa = new RSA();
     $keypair = $rsa->createKey($size);
     return new KeyPair(new PrivateKey($keypair['privatekey']), new PublicKey($keypair['publickey']));
 }
 protected static function doGenerateKeys($keySize = 2048)
 {
     $rsa = new Crypt_RSA();
     $rsa->setPrivateKeyFormat(Crypt_RSA::PRIVATE_FORMAT_PKCS1);
     $rsa->setPublicKeyFormat(Crypt_RSA::PUBLIC_FORMAT_PKCS1);
     defined('CRYPT_RSA_EXPONENT') || define('CRYPT_RSA_EXPONENT', 65537);
     defined('CRYPT_RSA_SMALLEST_PRIME') || define('CRYPT_RSA_SMALLEST_PRIME', 64);
     return $rsa->createKey($keySize);
 }
示例#8
0
 private function generateSshKeys()
 {
     $rsa = new RSA();
     $rsa->setPublicKeyFormat(RSA::PUBLIC_FORMAT_OPENSSH);
     $rsa->setPassword(\OC::$server->getConfig()->getSystemValue('secret', ''));
     $key = $rsa->createKey();
     // Replace the placeholder label with a more meaningful one
     $key['publicKey'] = str_replace('phpseclib-generated-key', gethostname(), $key['publickey']);
     return $key;
 }
示例#9
0
 /**
  * Create domain RSA keys
  *
  * @return KeyPair
  * @throws \Exception
  */
 public function createKeys()
 {
     $rsa = new RSA();
     $keys = $rsa->createKey(2048);
     if ($keys['partialkey'] === false) {
         $this->domainKeys = new KeyPair($keys['privatekey'], $keys['publickey']);
     } else {
         throw new \Exception('CPU was to slow, we\'ve not yet coded this part.');
     }
     return $this->domainKeys;
 }
示例#10
0
 /**
  * Generate a 4096 bits RSA private key
  * @return array the PEM-encoded version of the unprotected private and public keys.
  */
 function genRsa()
 {
     $rsa = new RSA();
     $privKey = $rsa->createKey(4096);
     // TODO handle timeout?
     if (isset($privKey["partialkey"])) {
         unset($privKey["partialkey"]);
     }
     return $privKey;
     // hash with privatekey and publickey
 }
示例#11
0
 public static function generate($bits = 2048, $password = '')
 {
     $bits = (int) $bits;
     $rsa = new RSA();
     if (!empty($password)) {
         $rsa->setPassword($password);
     }
     $keys = $rsa->createKey($bits);
     $publicKey = new SshPublicKey($keys['publickey']);
     $privateKey = new SshPrivateKey($keys['privatekey'], $password);
     return new SshKeyPair($publicKey, $privateKey);
 }
 /**
  * @Route("/asd", name="homepage")
  */
 public function indexAction(Request $request)
 {
     $request = $this->get('request');
     $defaultData = array('name' => 'Type your file name here');
     $form = $this->createFormBuilder($defaultData)->add('name', 'text')->add('file', 'file', array('mapped' => false))->add('submit', 'submit')->getForm();
     if ($request->getMethod() == 'POST') {
         $form->handleRequest($this->get('request'));
         if ($form->isValid()) {
             // perform some action, such as saving the task to the database
             $data = $form->getData();
             if ($form['file']->getData()) {
                 $filename = $form['file']->getData()->getClientOriginalName();
                 $uploadDir = dirname($this->container->getParameter('kernel.root_dir')) . '/web/bundles/framework/upload';
                 $form['file']->getData()->move($uploadDir, $filename);
                 $link = '/web/bundles/framework/upload' . '/' . $filename;
             }
         }
         $inputFile = $request->files->get('cache.xml');
         return $this->render('default/index.html.twig', array('cipher' => "", 'plain' => "", 'rsacipher' => "", 'rsaplain' => "", 'rsapk' => "", 'form' => $form->createView(), 'link' => $link));
     } else {
         $des = new DES();
         echo gettype($des);
         $des->setKey('This is my secret key');
         $plaintext = 'asda sda sdas dasd asdasdada sd';
         $cipher = $des->encrypt($plaintext);
         $plain = $des->decrypt($cipher);
         $rsa = new RSA();
         $rsa->createKey(1024);
         $rsaplain = "encrypt using RSA";
         $key = $rsa->createKey(1024);
         $rsa->loadKey($key['publickey']);
         $rsacipher = $rsa->encrypt($rsaplain);
         $rsa->loadKey($key['privatekey']);
         $rsadec = $rsa->decrypt($rsacipher);
         // replace this example code with whatever you need
         return $this->render('default/index.html.twig', array('base_dir' => realpath($this->container->getParameter('kernel.root_dir') . '/..'), 'cipher' => $cipher, 'plain' => $plain, 'rsacipher' => $key['publickey'], 'rsaplain' => $key['privatekey'], 'rsapk' => $rsa->getPublicKey(), 'form' => $form->createView()));
     }
 }
示例#13
0
 public function onRun()
 {
     foreach ($this->loadPaths as $name => $path) {
         if (!class_exists($name, false) and !interface_exists($name, false)) {
             require $path;
         }
     }
     $this->loader->register(true);
     $rsa = new RSA();
     $this->logger->info("[BigBrother] Generating keypair");
     $rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
     $rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
     $keys = $rsa->createKey(1024);
     $this->setResult($keys);
 }
示例#14
0
 /**
  * Create and save a key pair for user
  *
  * @return KeyPair
  * @throws \Exception
  */
 public function createKeys()
 {
     $rsa = new RSA();
     $keys = $rsa->createKey(2048);
     if ($keys['partialkey'] === false) {
         $this->keyPair = new KeyPair($keys['privatekey'], $keys['publickey']);
         $this->writeToStorage('public.key', $this->keyPair->getPublic());
         $this->writeToStorage('private.key', $this->keyPair->getPrivate());
         $this->config('status', 'keys generated');
     } else {
         throw new \Exception('CPU was to slow, we\'ve not yet coded this part.');
     }
     $this->acme = new AcmeService(new AcmeClient($this->acmeServer, $this->keyPair), $this->keyPair);
     return $this->keyPair;
 }
示例#15
0
 public function testSaveSPKAC()
 {
     $privKey = new RSA();
     extract($privKey->createKey());
     $x509 = new X509();
     $x509->setPrivateKey($privatekey);
     $x509->setChallenge('...');
     $spkac = $x509->signSPKAC();
     $this->assertInternalType('array', $spkac);
     $this->assertInternalType('string', $x509->saveSPKAC($spkac));
     $x509 = new X509();
     $x509->setPrivateKey($privKey);
     $spkac = $x509->signSPKAC();
     $this->assertInternalType('array', $spkac);
     $this->assertInternalType('string', $x509->saveSPKAC($spkac));
 }
 public function onEnable()
 {
     $this->saveDefaultConfig();
     $keyFile = $this->getDataFolder() . "key.json";
     if (!is_file($keyFile)) {
         $dir = dirname($keyFile);
         if (!is_dir($dir)) {
             mkdir($dir, 0777, true);
         }
         $rsa = new RSA();
         $keys = $rsa->createKey(2048);
         file_put_contents($keyFile, json_encode($keys, JSON_PRETTY_PRINT | JSON_BIGINT_AS_STRING));
     } else {
         $keys = json_decode(file_get_contents($keyFile), true);
     }
     $listenerDir = $this->getDataFolder() . "listeners/";
     if (!is_dir($listenerDir)) {
         mkdir($listenerDir);
     }
     foreach (scandir($listenerDir) as $file) {
         if (is_file($listenerDir . $file) and substr($file, -4) === ".php") {
             require_once $listenerDir . $file;
             $contents = file_get_contents($listenerDir . $file);
             if (preg_match_all('/^class=([A-Za-z0-9_]+)$/m', $contents, $matches, PREG_PATTERN_ORDER)) {
                 $class = $matches[1][0];
                 try {
                     $reflection = new \ReflectionClass($class);
                     if (!$reflection->isInstantiable()) {
                         $this->getLogger()->error("Unable to instantiate class {$class} specified at vote listener {$file}!");
                         continue;
                     }
                     if (!$reflection->isSubclassOf("votifierpe\\VoteListener")) {
                         $this->getLogger()->error("Class {$class} of vote listener {$file} must implement votifierpe\\VoteListener but didn't!");
                         continue;
                     }
                     $this->listeners[] = $reflection->newInstance($this);
                 } catch (\ReflectionException $e) {
                     $this->getLogger()->error("Unable to load vote listener {$file}: unable to find specified listener class {$class}");
                     continue;
                 }
             }
         }
     }
     $this->tcp = new TCPListener($this, $this->getConfig()->get("port"), serialize($keys));
 }
示例#17
0
 /**
  * Generates a new key pair. Then stores the private key and returns the public key.
  *
  * @param int $keylength Desired key length in bits
  * @return array The public key as an associative array containing its exponent "e"
  *               and modulus "n" in hexadecimal representation.
  */
 public static function generateKeys($keylength)
 {
     $rsa = new RSA();
     $rsa->setPublicKeyFormat(RSA::PUBLIC_FORMAT_RAW);
     $keys = $rsa->createKey($keylength);
     static::deletePrivateKeyTable();
     // delete, if exists - future-proofing for layout changes
     static::createPrivateKeyTable();
     // create, if doesn't exist
     static::storePrivateKey($keys['privatekey']);
     $e = new BigInteger($keys['publickey']['e'], 10);
     $n = new BigInteger($keys['publickey']['n'], 10);
     $e = $e->toHex();
     $n = $n->toHex();
     $publickey = array('e' => $e, 'n' => $n);
     static::writePublicKeyJS($publickey);
     return $publickey;
 }
示例#18
0
 protected function createRSA()
 {
     $rsa = new RSA();
     $rsa->setPublicKeyFormat(RSA::PUBLIC_FORMAT_OPENSSH);
     $rsa->setComment($this->config['routerboard']['backupuser'] . "@backup");
     $key = $rsa->createKey(2048);
     if (!empty($key)) {
         // be safe
         $this->backupExistRSA();
         // create id_rsa.pub (public key)
         $this->fsys->dumpFile($this->config['system']['ssh-dir'] . DIRECTORY_SEPARATOR . 'id_rsa.pub', $key['publickey']);
         // create id_rsa (private key)
         $this->fsys->dumpFile($this->config['system']['ssh-dir'] . DIRECTORY_SEPARATOR . 'id_rsa', $key['privatekey']);
         // set permissions -rw-------
         $this->fsys->chmod($this->config['system']['ssh-dir'] . DIRECTORY_SEPARATOR . 'id_rsa', 0600);
         $this->fsys->chmod($this->config['system']['ssh-dir'] . DIRECTORY_SEPARATOR . 'id_rsa.pub', 0600);
         // backup existing RSA files for sure.
         $this->backupExistRSA('routerboard-backup');
         $this->logger->log("The SSH-RSA public key has been created. Never delete those files! (id_rsa,id_rsa.pub)", $this->logger->setNotice());
         return;
     }
     throw new Exception(get_class($this) . " can not create the ssh-rsa public key file!");
 }
示例#19
0
 public function generateKeys($token)
 {
     $rsa = new RSA();
     $rsa->setPrivateKeyFormat(RSA::PRIVATE_FORMAT_PKCS8);
     $rsa->setPublicKeyFormat(RSA::PUBLIC_FORMAT_PKCS8);
     $keys = $rsa->createKey(4096);
     $items = $this->entity_manager->getRepository('PasswordSafeBundle:SharedPassword')->findByReceiver($token->getUser());
     $rsaOld = new RSA();
     $rsaOld->loadKey($this->databaseService->getMeta($token)->get('privateKey'));
     $meta = $this->databaseService->getMeta($token);
     $meta->add('privateKey', $keys['privatekey']);
     $meta->add('publicKey', $keys['publickey']);
     $this->databaseService->saveMetaRow($token, $meta);
     $token->getUser()->setPublicKey($keys['publickey']);
     $this->entity_manager->persist($token->getUser());
     $this->entity_manager->flush();
     $rsa->loadKey($token->getUser()->getPublicKey());
     foreach ($items as $item) {
         $decrypted = $rsaOld->decrypt($item->getEncryptedData());
         $item->setEncryptedData($rsa->encrypt($decrypted));
         $this->entity_manager->persist($item);
     }
     $this->entity_manager->flush();
 }
示例#20
0
文件: Keys.php 项目: fodorxyz/fodor
 public function getPair()
 {
     $installationUuid = $this->name;
     $publicKeyName = $this->getPublicKeyPath();
     $privateKeyName = $this->getPrivateKeyPath();
     if (Storage::exists($publicKeyName) === false || Storage::exists($privateKeyName) === false) {
         $rsa = new RSA();
         $rsa->setPublicKeyFormat(RSA::PUBLIC_FORMAT_OPENSSH);
         $rsa->setComment('*****@*****.**');
         $keys = $rsa->createKey(2048);
         $privateKey = $keys['privatekey'];
         $publicKey = $keys['publickey'];
         Storage::disk('local')->put($privateKeyName, $privateKey);
         Storage::disk('local')->put($publicKeyName, $publicKey);
     }
     return ['public' => $publicKeyName, 'private' => $privateKeyName];
     /*$sshConnection = ssh2_connect('mycloud.smellynose.com', 22, array('hostkey'=>'ssh-rsa'));
       $sshSuccess = ssh2_auth_pubkey_file(
           $sshConnection,
           'ahindle',
           storage_path('app/' . $publicKeyName),
           storage_path('app/' . $privateKeyName)
       );*/
 }
示例#21
0
 public static function create($type, $host, $port, $username, $password, &$key)
 {
     $connection = new Connection($type, $host, $port, $username, $password);
     $rsa = new RSA();
     //$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
     //$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
     //define('CRYPT_RSA_EXPONENT', 65537);
     //define('CRYPT_RSA_SMALLEST_PRIME', 64); // makes it so multi-prime RSA is used
     extract($rsa->createKey());
     // == $rsa->createKey(1024) where 1024 is the key size
     $key = $privatekey;
     $connection->publicKey = $publickey;
     return $connection;
 }
示例#22
0
文件: Openpgp.php 项目: horde/horde
 /**
  * Generate a RSA secret key (sub)packet.
  *
  * @param integer $keylength   RSA keylength.
  * @param string $packet_type  Secret key packet to create.
  *
  * @return OpenPGP_SecretKeyPacket  Secret key packet object.
  */
 protected function _generateSecretKeyPacket($keylength, $packet_type)
 {
     $rsa = new Crypt\RSA();
     $k = $rsa->createKey($keylength);
     $rsa->loadKey($k['privatekey']);
     return new $packet_type(array('n' => $rsa->modulus->toBytes(), 'e' => $rsa->publicExponent->toBytes(), 'd' => $rsa->exponent->toBytes(), 'p' => $rsa->primes[1]->toBytes(), 'q' => $rsa->primes[2]->toBytes(), 'u' => $rsa->coefficients[2]->toBytes()));
 }
示例#23
0
文件: Utils.php 项目: Apretaste/Core
 /**
  * Regenerate and return the private and public keys for a user
  *
  * @author salvipascual
  * @param String $email
  * @return Array(privatekey, publickey)
  * */
 public function recreateRSAKeys($email)
 {
     // create the public and private keys
     $rsa = new RSA();
     $rsa->setPublicKeyFormat(RSA::PUBLIC_FORMAT_OPENSSH);
     $keys = $rsa->createKey();
     $privatekey = $keys['privatekey'];
     $publickey = $keys['publickey'];
     // update the new keys or create a new pair
     $connection = new Connection();
     $connection->deepQuery("INSERT INTO `keys` (email, privatekey, publickey) VALUES('{$email}', '{$privatekey}', '{$publickey}') ON DUPLICATE KEY UPDATE privatekey='{$privatekey}', publickey='{$publickey}', last_usage=CURRENT_TIMESTAMP");
     // return the new keys
     return array("privatekey" => $privatekey, "publickey" => $publickey);
 }