codeaken / sshkey
用于操作和生成SSH密钥的库
1.2
2016-09-27 13:58 UTC
Requires
- php: >=5.4.0
- phpseclib/phpseclib: ^2.0
Requires (Dev)
- phpunit/phpunit: 4.4.*
This package is not auto-updated.
Last update: 2024-09-23 17:47:37 UTC
README
此库允许您在PHP中操作和生成公钥和私钥。
- 从文件和其他来源(如数据库)读取密钥
- 在密钥格式之间转换
- 获取公钥指纹
- 生成新的密钥对
所有密钥操作都依赖于phpseclib。
安装
在您的composer.json
中添加此包,然后运行composer update
"require": {
...
"codeaken/sshkey": "1.*"
...
},
用法
以下示例基于以下假设
- 库已自动加载,例如通过在项目中包含
vendor/autoload.php
- 您当前目录中有一个名为
id_rsa
的密钥对(私钥)和id_rsa.pub
(公钥)。私钥未加密。 - 当前目录中有一个名为
id_encrypted_rsa
的加密私钥,受密码abc123
保护
从文件中读取密钥
<?php // Read in the public and private keys $publicKey = SshPublicKey::fromFile('id_rsa.pub'); $privateKey = SshPrivateKey::fromFile('id_rsa'); $encryptedPrivateKey = SshPrivateKey::fromFile('id_encrypted_rsa', 'abc123'); // Try to read a key that does not exists; will throw a FileNotFoundException try { $missingKey = SshPublicKey::fromFile('nosuchkey.pub'); } catch (Codeaken\SshKey\Exception\FileNotFoundException $e) { echo 'Could not find the key'; } // Try to read an encrypted private key using the wrong password; will throw a // LoadKeyException try { $encryptedKey = SshPrivateKey::fromFile('id_encrypted_rsa', 'wrongpass'); } catch (Codeaken\SshKey\Exception\LoadKeyException $e) { echo 'Could not decrypt the private key'; }
从非文件源读取密钥
<?php // In this case we will read the key data from a file for simplicity but it // could come from a database or some other source $publicKeyData = file_get_contents('id_rsa.pub'); $publicKey = new SshPublicKey($publicKeyData); $encryptedPrivateKeyData = file_get_contents('id_encrypted_rsa'); $privateKey = new SshPrivateKey($encryptedPrivateKeyData, 'abc123');
获取公钥指纹和注释
<?php $publicKey = SshPublicKey::fromFile('id_rsa.pub'); echo $publicKey->getFingerprint(); echo $publicKey->getComment();
生成新的密钥对
<?php // 1024 bits and no passphrase $keyPair1 = SshKeyPair::generate(1024); // 2048 bits and a passphrase of abc123 $keyPair2 = SshKeyPair::generate(2048, 'abc123'); echo $keyPair2->getPrivateKey()->getKeyData(SshKey::FORMAT_PKCS8); echo $keyPair2->getPublicKey()->getKeyData(SshKey::FORMAT_OPENSSH);
将密钥保存到文件
<?php $keyPair = SshKeyPair::generate(); $publicKey = $keyPair->getPublicKey(); $privateKey = $keyPair->getPrivateKey(); file_put_contents('id_new_rsa.pub', $publicKey->getKeyData(SshKey::FORMAT_OPENSSH)); file_put_contents('id_new_rsa', $privateKey->getKeyData(SshKey::FORMAT_PKCS8));
许可协议
SshKey遵循MIT许可协议。
版权所有 2014 Magnus Johansson