自制了一个PHP RSA加密的一个类

前言

原文章地址:https://www.iczrx.cn/archives/82/
之前做了一个php通过RSA加密的一个文章

代码比较多也比较繁琐

所以现在新做了一个,放到了一个类里面

可以引用了直接调用,只需要配置公私钥即可

可以通过公私钥进行加解密

源码部分

Config.php

<?php
//ps:公钥和私钥不需要起始符,且必须保持内容为同一行
//公钥内容
$pubkey_content = "";

//私钥内容
$prikey_content = "";
?>

Keys.php

<?php
//定义前缀
$pub_pre = '-----BEGIN PUBLIC KEY-----';
$pub_suf = '-----END PUBLIC KEY-----';
$pri_pre = '-----BEGIN RSA PRIVATE KEY-----';
$pri_suf = '-----END RSA PRIVATE KEY-----';

//证书内容
require_once "Config.php";

//组合公私钥
$pubkey = $pub_pre . "\n" . $pubkey_content . "\n" . $pub_suf;
$prikey = $pri_pre . "\n" . $prikey_content . "\n" . $pri_suf;

//加密解密部分
class Keys {
  
    //通过公钥加密方法
    public function encrypts_pubkey($text) {
        global $pubkey;
        $result = "";
        openssl_public_encrypt($text,$result,$pubkey);
        return base64_encode($result);
    }
  
    //通过私钥解密方法
    public function decrypts_prikey($text) {
        global $prikey;
        $result = "";
        openssl_private_decrypt(base64_decode($text),$result,$prikey);
        return $result;
    }
  
    //通过私钥加密方法
    public function encrypts_prikey($text) {
        global $prikey;
        $result = "";
        openssl_private_encrypt($text,$result,$prikey);
        return base64_encode($result);
    }
  
    //通过公钥解密方法
    public function decrypts_pubkey($text) {
        global $pubkey;
        $result = "";
        openssl_public_decrypt(base64_decode($text),$result,$pubkey);
        return $result;
    }
}

使用这个类

在php中引用Keys.php

如下面代码所示:

<?php
require_once "Keys.php";

//加密内容
$content = "晚夜的个人博客";

$keys = new Keys;
echo $keys->encrypts_pubkey($content);
?>

这个代码的意思就是用公钥加密一段内容

输出结果为:

一段长文本

想要解密时就将密文输进去,调用decrypts_prikey这个方法

如下面代码所示:

<?php
require_once "Keys.php";

//加密内容
$content = "jODHYUmAXehrD5mC63HuNC4J8qkmbCTtqC1AHhgr4la5tmCr0R8oOlf/cdYgRs6dNVNrbMYgyrQcuGZYvNlPdPQ78zK6GcW/n60W/lXpAtpoOR15WqKK1LaEFru2arf1YF2cLvXgt2+G2nc2/Keo4lIoFs4TqYvlVjs/47ZoOvjeglkHIvtfYwaKgvNtDlXMo1uG7BXJ761jmeExxvSEaom8q02h/MHwe5mXP1/uajbt192DWt183KrRSz7k1Au7w8FhCYUpN6pd3Kd2SgBqkcpyqTL1zWkrGBNIawFpMsurvgsSjNQXj0+JOBsQ+1Y882Ys5WgTuLmrTwlebLJLjw==";

$keys = new Keys;
echo $keys->decrypts_prikey($content);
?>

输出结果即为“晚夜的个人博客“

同样的,使用私钥加密和公钥解密只需要调用encrypts_prikey和decrypts_pubkey即可

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值