php 的rsa加密与解密

系统:centos6.5

linux系统生成公私钥对方法:

openssl genrsa -out rsa_private_key.pem 1024
openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out private_key.pem
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
第一条命令生成原始 RSA私钥文件 rsa_private_key.pem,第二条命令将原始 RSA私钥转换为 pkcs8格式,第三条生成RSA公钥 rsa_public_key.pem

下面是代码:

公钥加密私钥解密

        $source='abcde';
        $pkeyid=file_get_contents(DIR_BASE.'/rsa_key/rsa_public_key.pem', 'r');
        $res = openssl_get_publickey($pkeyid);
        openssl_public_encrypt($source,$crypttext,$res);
        echo $crypttext;
        $pkeyid=file_get_contents(DIR_BASE.'/rsa_key/rsa_private_key.pem', 'r');
        $res2 = openssl_get_privatekey($pkeyid);
        if(openssl_private_decrypt($crypttext,$data,$res2)){
            echo $data;
        }else{
            echo "false";
        }

私钥加密公钥解密

$source='abcde';
        $pkeyid=file_get_contents(DIR_BASE.'/rsa_key/rsa_private_key.pem', 'r');
        $res = openssl_get_privatekey($pkeyid);
        openssl_private_encrypt($source,$crypttext,$res);
        echo $crypttext;
        $pkeyid=file_get_contents(DIR_BASE.'/rsa_key/rsa_public_key.pem', 'r');
        $res2 = openssl_get_publickey($pkeyid);
        if(openssl_public_decrypt($crypttext,$data,$res2)){
            echo $data;
        }else{
            echo "false";
        }



 

你可能感兴趣的:(php 的rsa加密与解密)