首頁 >php教程 >php手册 >rsa加密解密类库附示例-php&python版

rsa加密解密类库附示例-php&python版

WBOY
WBOY原創
2016-06-06 20:13:522154瀏覽

早期造个对象,写了个php的rsa帮助类库,先看使用方法 $keys = RsaHelper::new_rsa_key;//生成完key之后应该记录下key值,这里省略$privkey = $keys'privkey';$pubkey = $keys'pubkey';/* $privkey = '-----BEGIN PRIVATE KEY-----MIICdwIBADANBgkqhkiG9w0BA

 早期造个对象,写了个php的rsa帮助类库,先看使用方法

$keys = RsaHelper::new_rsa_key();
 
//生成完key之后应该记录下key值,这里省略
$privkey = $keys['privkey'];
$pubkey  = $keys['pubkey'];
 
/* $privkey = '-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKX0cHYmXyHhIx5/
k6GMneVKpUDsqP2PdKFGollWYCbxJUAHPsHsjILGI0ucGnC+VpfKVX6DEagoRBZv
tz+nnpcreVPtNbKMNzhukSY3Mt7Fo1rMaj0pbsaMom1noQjsKJlVgz6akP7RMm4W
zpnMvcDq/9PucfCQP1FGZTbg1hUxAgMBAAECgYBeGam/ROjChC9utrZWby6E+nuT
wd3c0QA4Bp49+/1Pd4NAuBr8yQ2vhXwz/lL7xOHC9ibeMqHLcPGSq0wEGx6P/XWM
0Ldpwu6cWv4qOdHdBDdqrO6mkyBljt4sq1WtTnkLgZ0cCTTeVnnFDmlc9Zr9oT5k
UezOEb55GziRD5XUxQJBANLx3kUjOFRyR1I/wZYHHJkcm8pSgpDe4b1G60orZa9J
nbUTM+cIvmNKzm99m9aIMvgjk/LBydpxV7W5YYDxHrcCQQDJZpcu5OPWNJ3TdrrK
KNa1lfUo5Vb0sCgpTueZdwngBr043XRTyJHqjziX/9Z19UWrE9Gz6U1Klpa7SBYo
O4NXAkEArsKRCahXJ6cRrXOClx/HMpY//0uCPjFYxa32ipkPgjwz+uswycw1px83
jah7ri1iRK99B9ZCu8XBC53MyL16WwJAISu+dsDILb2YyP1jImy7gEjkignL2p0w
4CzYxFPw0m8Jt1XyFOKR9doE7jP69I6jHNw0y7b/Peuzg8EJtTKoHQJBAITAjM7Q
QnIEgYHvw3gaQI8/6992Y0DSMaHt50peI6uJoMV+X9IcjY1eFUSOHV8nb0uI8xQ7
4SbU2yvLPTqUk50=
-----END PRIVATE KEY-----';
 
$pubkey = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCl9HB2Jl8h4SMef5OhjJ3lSqVA
7Kj9j3ShRqJZVmAm8SVABz7B7IyCxiNLnBpwvlaXylV+gxGoKEQWb7c/p56XK3lT
7TWyjDc4bpEmNzLexaNazGo9KW7GjKJtZ6EI7CiZVYM+mpD+0TJuFs6ZzL3A6v/T
7nHwkD9RRmU24NYVMQIDAQAB
-----END PUBLIC KEY-----'; */
 
//初始化rsaobject
RsaHelper::init($privkey, $pubkey);
 
//原文
$data = 'hello';
 
//私钥加密示例
$encode = RsaHelper::priv_encode($data);
$ret = RsaHelper::pub_decode($encode);
var_dump($ret);
 
//公钥加密示例
$encode = RsaHelper::pub_encode($data);
$ret = RsaHelper::priv_decode($encode);
var_dump($ret);

      类库源码如下

class RsaHelper{
    private static $_privkey = '';
    private static $_pubkey = '';
    private static $_isbase64 = false;
 
    /**
     * 初始化key值
     * @param  string  $privkey  私钥
     * @param  string  $pubkey   公钥
     * @param  boolean $isbase64 是否base64编码
     * @return null
     */
    public static function init($privkey, $pubkey, $isbase64=false){
        self::$_privkey = $privkey;
        self::$_pubkey = $pubkey;
        self::$_isbase64 = $isbase64;
    }
 
    /**
     * 私钥加密
     * @param  string $data 原文
     * @return string       密文
     */
    public static function priv_encode($data){
        $outval = '';
        $res = openssl_pkey_get_private(self::$_privkey);
        openssl_private_encrypt($data, $outval, $res);
        if(self::$_isbase64){
            $outval = base64_encode($outval);
        }
        return $outval;
    }
 
    /**
     * 公钥解密
     * @param  string $data 密文
     * @return string       原文
     */
    public static function pub_decode($data){
        $outval = '';
        if(self::$_isbase64){
            $data = base64_decode($data);
        }
        $res = openssl_pkey_get_public(self::$_pubkey);
        openssl_public_decrypt($data, $outval, $res);
        return $outval;
    }
 
    /**
     * 公钥加密
     * @param  string $data 原文
     * @return string       密文
     */
    public static function pub_encode($data){
        $outval = '';
        $res = openssl_pkey_get_public(self::$_pubkey);
        openssl_public_encrypt($data, $outval, $res);
        if(self::$_isbase64){
            $outval = base64_encode($outval);
        }
        return $outval;
    }
 
    /**
     * 私钥解密
     * @param  string $data 密文
     * @return string       原文
     */
    public static function priv_decode($data){
        $outval = '';
        if(self::$_isbase64){
            $data = base64_decode($data);
        }
        $res = openssl_pkey_get_private(self::$_privkey);
        openssl_private_decrypt($data, $outval, $res);
        return $outval;
    }
 
    /**
     * 创建一组公钥私钥
     * @return array 公钥私钥数组
     */
    public static function new_rsa_key(){
        $res = openssl_pkey_new();
        openssl_pkey_export($res, $privkey);
        $d= openssl_pkey_get_details($res);
        $pubkey = $d['key'];
 
        return array(
            'privkey' => $privkey,
            'pubkey'  => $pubkey
        );
    }
}

      妈蛋,win平台下的php protobuf折腾死我了,又改成py了,所以,python版的rsa加密辅助类来了

def new_keys():
    (bob_pub, bob_priv) = rsa.newkeys(1024)
    return {'pubkey':bob_pub.save_pkcs1(), 'privkey':bob_priv.save_pkcs1()}
 
class RsaHelper:
 
    def __init__(self, privkey, pubkey):
        self._privkey = privkey.decode('string-escape')
        self._pubkey = pubkey.decode('string-escape')
 
    def encode_priv(self, data):
        privkey = rsa.PrivateKey.load_pkcs1(self._privkey)
        crypto = rsa.encrypt(data, privkey)
        return crypto
 
    def decode_pub(self, data):
        pubkey = rsa.PublicKey.load_pkcs1(self._pubkey)
        msg = rsa.decrypt(data, pubkey)
        return msg
 
    def decode_priv(self, data):
        privkey = rsa.PrivateKey.load_pkcs1(self._privkey)
        msg = rsa.decrypt(data, privkey)
        return msg
 
    def encode_pub(self, data):
        pubkey = rsa.PublicKey.load_pkcs1(self._pubkey)
        crypto = rsa.encrypt(data, pubkey)
        return crypto
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn