php下的RSA算法实现

PHP实现RSA算法 sample-php-rsa PHP RSA加解密原理实现(不调用php内置的rsa函数,纯方法实现) 原理参考: RSA算法原理 https://zhuanlan.zhihu.com/p/48249182 示例: $rsa = new sample_rsa(); $key = $rsa->createKey(); $encrypt_data = $rsa->encrypt_data($key, 'test'); echo $encrypt_data.PHP_EOL; $decrypt_d 阅读详情
/*
* Implementation of the RSA algorithm
* (C) Copyright 2004 Edsko de Vries, Ireland
*
* Licensed under the GNU Public License (GPL)
*
* This implementation has been verified against [3]
* (tested Java/PHP interoperability).
*
* References:
* [1] "Applied Cryptography", Bruce Schneier, John Wiley & Sons, 1996
* [2] "Prime Number Hide-and-Seek", Brian Raiter, Muppetlabs (online)
* [3] "The Bouncy Castle Crypto Package", Legion of the Bouncy Castle,
* (open source cryptography library for Java, online)
* [4] "PKCS #1: RSA Encryption Standard", RSA Laboratories Technical Note,
* version 1.5, revised November 1, 1993

*/

/*
* Functions that are meant to be used by the user of this PHP module.
*
* Notes:
* - $key and $modulus should be numbers in (decimal) string format
* - $message is expected to be binary data
* - $keylength should be a multiple of 8, and should be in bits
* - For rsa_encrypt/rsa_sign, the length of $message should not exceed
* ($keylength / 8) - 11 (as mandated by [4]).
* - rsa_encrypt and rsa_sign will automatically add padding to the message.
* For rsa_encrypt, this padding will consist of random values; for rsa_sign,
* padding will consist of the appropriate number of 0xFF values (see [4])
* - rsa_decrypt and rsa_verify will automatically remove message padding.
* - Blocks for decoding (rsa_decrypt, rsa_verify) should be exactly
* ($keylength / 8) bytes long.
* - rsa_encrypt and rsa_verify expect a public key; rsa_decrypt and rsa_sign
* expect a private key.

*/

function rsa_encrypt($message, $public_key, $modulus, $keylength)
{

    $padded = add_PKCS1_padding($message, true, $keylength / 8);
    $number = binary_to_number($padded);
    $encrypted = pow_mod($number, $public_key, $modulus);
    $result = number_to_binary($encrypted, $keylength / 8);
    
    return $result;
}


function rsa_decrypt($message, $private_key, $modulus, $keylength)
{

    $number = binary_to_number($message);
    $decrypted = pow_mod($number, $private_key, $modulus);
    $result = number_to_binary($decrypted, $keylength / 8);

    return remove_PKCS1_padding($result, $keylength / 8);
}


function rsa_sign($message, $private_key, $modulus, $keylength)
{

    $padded = add_PKCS1_padding($message, false, $keylength / 8);
    $number = binary_to_number($padded);
    $signed = pow_mod($number, $private_key, $modulus);
    $result = number_to_binary($signed, $keylength / 8);

    return $result;
}


function rsa_verify($message, $public_key, $modulus, $keylength)
{

    return rsa_decrypt($message, $public_key, $modulus, $keylength);
}


/*
* Some constants

*/

define("BCCOMP_LARGER", 1);

/*
* The actual implementation.
* Requires BCMath support in PHP (compile with --enable-bcmath)

*/

//--
// Calculate (p ^ q) mod r
//
// We need some trickery to [2]:
// (a) Avoid calculating (p ^ q) before (p ^ q) mod r, because for typical RSA
// applications, (p ^ q) is going to be _WAY_ too large.
// (I mean, __WAY__ too large - won't fit in your computer's memory.)
// (b) Still be reasonably efficient.
//
// We assume p, q and r are all positive, and that r is non-zero.
//
// Note that the more simple algorithm of multiplying $p by itself $q times, and
// applying "mod $r" at every step is also valid, but is O($q), whereas this
// algorithm is O(log $q). Big difference.
//
// As far as I can see, the algorithm I use is optimal; there is no redundancy
// in the calculation of the partial results.
//--

function pow_mod($p, $q, $r)
{

    // Extract powers of 2 from $q
$factors = array();
    $div = $q;
    $power_of_two = 0;
    while(bccomp($div, "0") == BCCOMP_LARGER)
    {

        $rem = bcmod($div, 2);
        $div = bcdiv($div, 2);
    
        if($rem) array_push($factors, $power_of_two);
        $power_of_two++;
    }


    // Calculate partial results for each factor, using each partial result as a
    // starting point for the next. This depends of the factors of two being
    // generated in increasing order.

$partial_results = array();
    $part_res = $p;
    $idx = 0;
    foreach($factors as $factor)
    {

        while($idx < $factor)
        {

            $part_res = bcpow($part_res, "2");
            $part_res = bcmod($part_res, $r);

            $idx++;
        }
        
        array_pus(
$partial_results, $part_res);
    }


    // Calculate final result
$result = "1";
    foreach($partial_results as $part_res)
    {

        $result = bcmul($result, $part_res);
        $result = bcmod($result, $r);
    }


    return $result;
}


//--
// Function to add padding to a decrypted string
// We need to know if this is a private or a public key operation [4]
//--

function add_PKCS1_padding($data, $isPublicKey, $blocksize)
{

    $pad_length = $blocksize - 3 - strlen($data);

    if($isPublicKey)
    {

        $block_type = "/x02";
    
        $padding = "";
        for($i = 0; $i < $pad_length; $i++)
        {

            $rnd = mt_rand(1, 255);
            $padding .= chr($rnd);
        }
    }

    else
    {

        $block_type = "/x01";
        $padding = str_repeat("/xFF", $pad_length);
    }

    
    return "/x00" . $block_type . $padding . "/x00" . $data;
}


//--
// Remove padding from a decrypted string
// See [4] for more details.
//--

function remove_PKCS1_padding($data, $blocksize)
{

    assert(strlen($data) == $blocksize);
    $data = substr($data, 1);

    // We cannot deal with block type 0
if($data{0} == '/0')
        die("Block type 0 not implemented.");

    // Then the block type must be 1 or 2
assert(($data{0} == "/x01") || ($data{0} == "/x02"));

    // Remove the padding
$offset = strpos($data, "/0", 1);
    return substr($data, $offset + 1);
}


//--
// Convert binary data to a decimal number
//--

function binary_to_number($data)
{

    $base = "256";
    $radix = "1";
    $result = "0";

    for($i = strlen($data) - 1; $i >= 0; $i--)
    {

        $digit = ord($data{$i});
        $part_res = bcmul($digit, $radix);
        $result = bcadd($result, $part_res);
        $radix = bcmul($radix, $base);
    }


    return $result;
}


//--
// Convert a number back into binary form
//--

function number_to_binary($number, $blocksize)
{

    $base = "256";
    $result = "";

    $div = $number;
    while($div > 0)
    {

        $mod = bcmod($div, $base);
        $div = bcdiv($div, $base);
        
        $result = chr($mod) . $result;
    }


    return str_pad($result, $blocksize, "/x00", STR_PAD_LEFT);
}

?>
解决用加速器以后,电脑无法连接网络的问题 相信很多朋友也遇到过,用加速器以后,电脑网络直接断了,或者访问外网时打不开的情况解决办法是。 阅读详情

相关推荐

Nvidia Isaac Sim图形界面 入门教程 2024(3)

在使用Isaac Sim时,最先接触到的应该是它的图形界面,此处将简单介绍图形界面中常用的一些组件:Isaac Sim的界面的常用内容可以分为几个板块。

m0_56661101的博客 4548

php之RSA加密解密

介绍 RSA算法属于非对称加密算法,非对称加密算法需要两个秘钥:公开密钥(publickey)和私有秘钥(privatekey).公开密钥和私有秘钥是一对,如果公开密钥对数据进行加密,只有用对应的私有秘钥才能解密;如果私有秘钥对数据进行加密那么只有用对应的公开密钥才能解密.因为加密解密使用的是两个不同的秘钥,所以这种算法叫做非对称加密算法.简单的说就是公钥加密私钥解密,私钥加密公钥解密 准备 需要给PHP打开OpenSSL模块 代码 /** * RSA算法属于非对称加密算法,非对称加密算法需要两个秘钥:公

工作中学习,学习中进步 1万+

Python气象雷达数据处理实战:用PyCINRAD从基数据到PPI图的完整流程

本文详细介绍了使用PyCINRAD库处理气象雷达基数据并生成PPI图的完整流程,涵盖环境配置、数据读取、反射率与速度数据提取、可视化优化等关键步骤。通过实战案例演示如何从原始雷达数据到专业级PPI图像生成,为气象研究和业务应用提供高效解决方案。

yog99的博客 762

RSA签名类,我还不太会用

<?php namespace jplt; /** * RSA签名类 */ class Rsa { public $publicKey = ''; public $privateKey = ''; private $_privKey; /** * * private key */ private $_pubKey; /** * * public key */ private $_keyPath;

王兆镇的博客 591

群晖NAS从入门到精通的所有帖子汇总,只要这一篇就够了

本站陆陆续续的转载、原创帖子也有十几二十篇了,从不同的角度对群晖NAS的各种骚操作都有深入的讲解,虽然很多文章都不是讲的很深入,但是针对小白入门已经是足够了,希望对小白来说是一个入门,群晖NAS的大佬们勿喷,哪里写的不对的,请随时留言西安SEO优化站长一定在第一时间纠正修改。

西安SEO优化网站资源 8万+

ERDAS 2022与ArcGIS共存安装教程:如何避免端口冲突(详细配置步骤)

本文提供了一份详细的ERDAS 2022与ArcGIS共存安装教程,核心在于解决两者因FlexNet许可证服务器导致的端口冲突问题。通过分步指导,包括检查现有端口占用、修改ERDAS许可证文件端口号、配置防火墙及客户端设置,确保两款专业GIS与遥感软件能在同一系统上稳定运行。

weixin_29279047的博客 255

PHP加密专题-通过RSA实现加密解密

这仅仅是当今密码学主题的一个方面。对信息发送与接收人的真实身份的验证、对所发出/接收信息在事后的不可抵赖以及保障数据的完整性是现代密码学主题的另一方面。公开密钥密码体制对这两方面的问题都给出了出色的解答,并正在继续产生许多新的思想和方案。在公钥体制中,加密密钥不同于解密密钥。人们将加密密钥公之于众,谁都可以使用;而解密密钥只有解密人自己知道。迄今为止的所有公钥密码体系中,RSA系统是最著名、使用最广泛的一种。

wanyeaha的博客 2375

YOLOv12 改进 | Backbone改进 3

将CSP中的简单拼接改为可学习的特征选择门控,动态决定哪些特征流向下一层,同样再写这篇。:相比静态CSP的固定50/50分割,门控机制可学习0.3:0.7等最优比例。在输入端加入轻量SR模块,对下采样后的特征进行超分恢复,提升小目标检测能力。(小目标): 从 0.51 AP → 0.63 AP (+24%):采用ESPCN的高效亚像素卷积,避免传统插值的信息损失。:从通道级(SE)到空间级(Spatial)的多粒度控制。:结合浅层细节和深层语义,恢复小目标的纹理信息。

u012133341的博客 843

PHP非对称加密-RSA

PHP非对称加密-RSA工具类测试代码 前言: RSA,常说的非对称加密。加密解密密钥不一致,它们是成对出现,通常密钥生成是PEM格式。 公钥加密的私钥解密,私钥加密的要公钥解密。 往往私钥是不公开的,公钥是大家共享的。 相同内容,相同私钥每次加密后结果还会不一样。 通过公钥加密结果,必须私钥解密。 同样私钥加密结果,公钥可以解密。 RSA加密也是块加密,因此一样存在填充模式。pkcs#1与pkcs#8 默认填充方式是pkcs#1。 注:php 目前只支持 pkcs#1的填充模式 工具类 /**

weixin_46044420的博客 1229

提交 ieee 手稿出现:Do not include the Reviewer PDF with my submission 怎么办

IEEE投稿Reviewer PDF选项说明 投稿时出现的"Do not include the Reviewer PDF with my submission"选项控制是否附带评审专用PDF文件。Reviewer PDF是系统自动生成包含所有投稿材料的完整PDF,用于同行评审。建议保持默认不勾选状态,除非确认编辑部不需要该文件,否则可能影响审稿流程。勾选表示不附带此PDF,不勾选则会正常生成并提交该评审文件。

ZhangJiqun&191cm&85kg 2275

华为OD机试新系统真题【字符串压缩编码】

华为OD机试 新系统真题【字符串压缩编码】,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。华为OD机试真题【字符串压缩编码】多语言题解

qq_45776114的博客 364

PHP非对称加密(公钥加密私钥解密):RSA (RSA/ECB/PKCS1Padding)+base64_encode/bin2hex加密

所谓非对称,就是使用公钥/私钥加密,然后用对应的私钥/公钥解密 1.钥配对的公钥,私钥: //公钥(注意包括头(-----BEGIN PUBLIC KEY-----)尾(-----END PUBLIC KEY-----)标志) -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDbdq5NjtUEkAQ6wucPuhC0aRvSMsaX3GrhkwsLLdWZnVNVpkJRw yPFq9HJNuntRw7P9Sb3Tk.

因上努力,果上随缘 4731

嵌入式 AI 编程实战:从芯片到 AI 工具链---总结笔记

嵌入式 AI 编程实战:从芯片到 AI 工具链---总结笔记

weixin_42162924的博客 97

rsa.php 源代码,php下的RSA算法实现_php

/** Implementation of the RSA algorithm* (C) Copyright 2004 Edsko de Vries, Ireland** Licensed under the GNU Public License (GPL)*http://www.gaodaima.com/48106.htmlphp下的RSA算法实现_php* This implementatio...

weixin_39695490的博客 195

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

rsa算法模型的php代码,php下的RSA算法实现

/** PHP implementation of the RSA algorithm* (C) Copyright 2004 Edsko de Vries, Ireland** Licensed under the GNU Public License (GPL)** This implementation has been verified against [3]* (tested Java/...

weixin_31649177的博客 159

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

php rsa算法使用说明,php下的RSA算法实现

/** PHP implementation of the RSA algorithm* (C) Copyright 2004 Edsko de Vries, Ireland** Licensed under the GNU Public License (GPL)** This implementation has been verified against [3]* (tested Java/...

weixin_39823299的博客 191

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

RSA算法的简单实现——PHP

RSA算法的原理以及简单实现,结束了算法相关的欧拉函数,欧几里得和扩展欧几里得算法

ChenTest100的博客 763

PHP实现RSA算法对数据加密解密

最近在研究RSA在PHP中的实现,在百度上一搜,记录倒不少,但点进去一看,老半天也没发现可用的东西,很多都只是直接给出一个RSA类文件的内容,哥不想骂人啊,你说一个方法rsa_encrypt($message,$public_key, $modulus, $keylength),这第一个当然是要加密的信息,但后面几个呢?啥意思,无语,再说了,这公钥、私钥怎么获取呢? 当然这里的话,我

liujizhong的专栏 2289

rsa算法php,简化版(小素数版)RSA算法的PHP实现

0x00 前言我们这学期的课程《信息安全与保密》要求期末作业实现一个密码算法及对应的加解密系统,其中做RSA的要求实现加解密、数字签名。考虑到我因为太菜,当初遇到了不少问题,莆田搜索RSA算法实现想参考一下的时候找不到PHP版本的,所以我完成作业后打算自己整一篇以供有需要的后来者参考考虑到我们期末作业主要任务是“实现RSA加解密、数字签名”,故没有采用大整数运算,受PHP的数据精度限制,素数范围在...

weixin_29798625的博客 247

php rsa2签名,使用PHP实现RSA或RSA2算法的签名和验签

使用RSA算法除了加密解密之外(加密解密的代码可以查看本站PHP使用RSA算法加密解密数据这篇文章),在支付等接口方面通常还会用到生成签名和验证签名操作,下面是PHP代码:class RSA{/*** RSA签名* @param $data 待签名数据* @param $private_key 私钥字符串* return 签名结果*/function rsaSign($data, $privat...

weixin_39629093的博客 257

php rsa2验签,使用PHP实现RSA或RSA2算法的签名和验签

使用RSA算法除了加密解密之外(加密解密的代码可以查看本站PHP使用RSA算法加密解密数据 这篇文章),在支付等接口方面通常还会用到生成签名和验证签名操作,下面是PHP代码:class RSA{/*** RSA签名* @param $data 待签名数据* @param $private_key 私钥字符串* return 签名结果*/function rsaSign($data, $privat...

weixin_39638929的博客 300

php rsa签名验签,PHP实现RSA或RSA2算法的签名和验签

摘要:写了一个用PHP生成PSA和RSA2算法签名和验签的工具类,在支付等接口方面通常会用到,下面是代码:class RSA2{/*** RSA2签名...写了一个用PHP生成PSA和RSA2算法签名和验签的工具类,在支付等接口方面通常会用到,下面是代码:classRSA2{/***RSA2签名*@param$data待签名数据*@param$private_key私钥字符串*r...

weixin_39860975的博客 361

php api md5签名,PHP实现的MD5结合RSA签名算法实例

本文实例讲述了PHP实现的MD5结合RSA签名算法。分享给大家供大家参考,具体如下:class Md5RSA{/*** 利用约定数据和私钥生成数字签名* @param $data 待签数据* @return String 返回签名*/public function sign($data=''){if (empty($data)){return False;}$private_key = file_...

weixin_33042659的博客 359

使用PHP实现RSA算法的加密和解密

使用PHP实现RSA算法的加密和解密

casey的博客 1621
上一篇: PHP下如何对文件进行加锁
下一篇: PHP下得到客户端ip的方法
trip
博客等级 码龄25年 20粉丝 40原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值