phpにおけるrsa暗号化復号化

1772 ワード

    /**        
     * @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          "
", "
" $k = empty( $type ) ? "-----BEGIN PUBLIC KEY-----
" : "-----BEGIN RSA PRIVATE KEY-----
"; foreach ( str_split( $key , 64 ) as $str ) { $k .= $str . "
"; } $k .= empty( $type ) ? "-----END PUBLIC KEY-----" : "-----END RSA PRIVATE KEY-----"; return $k; }