php加密解密:RSA

加密

public function bank_public_encrypt($data){
		$pubKey = file_get_contents('rsa_public_key_2048.pem');
		$res = openssl_get_publickey($pubKey);
		$info = openssl_pkey_get_details($res);
		$num = $info['bits'];
		$plainData = str_split($data, $num / 8 - 11);
		$encrypted = '';
        foreach ($plainData as $chunk) {
            $str = '';
            $encryption = openssl_public_encrypt($chunk, $str, $pubKey, OPENSSL_PKCS1_PADDING);
            if ($encryption === false) {
                return false;
            }
            $encrypted .= $str;
        }
		openssl_free_key($res);
		$encrypt = base64_encode($encrypted);
		return $encrypt;
	}
//解密
public function bank_private_decrypt($data){
	$priKey = file_get_contents('rsa_private_key_2048.pem');
	$res = openssl_get_privatekey($priKey);
	$info = openssl_pkey_get_details($res);
	$num = $info['bits'];
	$decrypted = '';
	$plainData = str_split(base64_decode($data), $num / 8);
    foreach ($plainData as $chunk) {
        $str = '';
        $decryption = openssl_private_decrypt($chunk, $str, $res, OPENSSL_PKCS1_PADDING);
        if ($decryption === false) {
            return false;
        }
        $decrypted .= $str;
    }
	openssl_free_key($res);
	return $decrypted;
}

你可能感兴趣的:(PHP,加密解密)