/**获取私钥是否可用
* @return bool
*/
public function isPrivateKey()
{
if ( !openssl_pkey_get_private( $this -> privateKey ) ) {
return false;
}
return true;
}
/**获取公钥是否可用
* @return bool
*/
public function isPublicKey()
{
if ( !openssl_pkey_get_public( $this -> publicKey ) ) {
return false;
}
return true;
}
/**
* @param $str
* @param string $encrypt_data
*
* @return string
*/
public function publicKeyEncrypt( $str , $encrypt_data = '' )
{
openssl_public_encrypt( $str , $encrypt_data , $this -> publicKey );
return base64_encode( $encrypt_data );
}
/**
* @param $cipherText
* @param string $decrypted
*
* @return string
*/
public function privateKeyDecrypt( $cipherText , $decrypted = '' )
{
$cryptData = base64_decode( $cipherText );
openssl_private_decrypt( $cryptData , $decrypted , $this -> privateKey );
return $decrypted;
}
/**将字符串格式公私钥格式化为pem格式公私钥
*
* @param $key
* @param string $type
*
* @return string
*/
public static function stringToSecretKey( $key , $type = '' )
{
// 64个英文字符后接换行符"\n",最后再接换行符"\n"
$k = empty( $type ) ? "-----BEGIN PUBLIC KEY-----\n" : "-----BEGIN RSA PRIVATE KEY-----\n";
foreach ( str_split( $key , 64 ) as $str ) {
$k .= $str . "\n";
}
$k .= empty( $type ) ? "-----END PUBLIC KEY-----" : "-----END RSA PRIVATE KEY-----";
return $k;
}
网友评论