PHP RSA公钥和私钥加解密

发布于2017-12-23  2,003次阅读


直接上代码:

 

 

 

<?php
class RSA{  
    var $public_key = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCytbQ5xzaIt+CssGzqrNmgFEY3GuhLq0cQO9/iA8Mb0h6WwYPx3yX1k6Jbqp0OIap68kiz19hMKkvvzIfiw85Kj7ljxcqYqJjaKKZkXp1GKYwLCh4MjJtuGVn3C25oEiLW7lTbH6NmrMbwe+lTHzTBC0NGHdU97O9ojp8KQHFq5QIDAQAB
-----END PUBLIC KEY-----'; //公密钥  
    var $private_key = '-----BEGIN RSA PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALK1tDnHNoi34KywbOqs2aAURjca6EurRxA73+IDwxvSHpbBg/HfJfWToluqnQ4hqnrySLPX2EwqS+/Mh+LDzkqPuWPFypiomNoopmRenUYpjAsKHgyMm24ZWfcLbmgSItbuVNsfo2asxvB76VMfNMELQ0Yd1T3s72iOnwpAcWrlAgMBAAECgYEApg6jfkC3UskR00VIn7OnsNDGAfRVv+JScSpBucFnLdXMKKd+lGSW4B+j8OuTbosn34B8v+gkC3oN/7Ac4ECz0RIoUjYUecA1ywIjVe4hXgGSawJGwnLtwUW1ne8W9FZblMcAoTyKVczahJS9uHOFPfWo0TUvVlkduln63lKwOwECQQDyYwIpWca+uVkKeck+WzMDkCGOjBycPb8oj5HLL7vpkQvXHStglNyABoTXm9EBqAKfbVvH1xxVBsyR3/2n0n8lAkEAvL8o8jVWLf5haKOmQXm2NvyYRkvI+q96/fYuBtANJ/XV0yXG+MGKiRmNX0ZYGfgroOOE/X7s9JksBzeSSbRQwQJBALssGY809HRzTH76bJzqcApgUolxSOaeB++abkspIULL7wi+TbDXQy7Z2dtlR5Cv3Naf7C/1vLsr9Ozwuz/NHMECQEUK1AqNciHO7IjfXACVag8BJR6JuFHjAOWHONzrG/TjGz1qkzcJbQirnSgdzjppqmPm9g3YcQskQJO/QzbMy8ECQBKwVvZz+OBeSyNEUa4b71Z0JmMgCZIH3yOCbjT13bHgrewWc1cb1pBjkd3tiOHKL2Ljk6QeP99opaCQWuKcMxI=
-----END RSA PRIVATE KEY-----'; //私密钥  
   
    /** 
     * 用私密钥加密 
     */  
    public function private_encrypt($input) {  
        $privateKey = openssl_pkey_get_private($this->private_key);
        openssl_private_encrypt($input,$output, $privateKey);  
        return base64_encode($output);  
    }  
    /** 
     * 解密 私密钥加密后的密文 
     */  
    public function public_decrypt($input) {  
        $public_key = openssl_pkey_get_public($this->public_key);
        openssl_public_decrypt(base64_decode($input),$output,$public_key);  
        return $output;  
    }  
    /** 
     * 用公密钥加密 
     */  
    public function public_encrypt($input) {  
        $public_key = openssl_pkey_get_public($this->public_key);
        openssl_public_encrypt($input,$output,$public_key);  
        return base64_encode($output);  
    }  
    /** 
     * 解密 公密钥加密后的密文 
     */  
    public function private_decrypt($input) {  
        $privateKey = openssl_pkey_get_private($this->private_key);
        openssl_private_decrypt(base64_decode($input),$output,$privateKey);  
        return $output;  
    }  
}  
  
$rsa = new RSA();  
//  
$str = '加密解密';  
$str = $rsa->public_encrypt($str); //用公密钥加密  
echo $str,'</br>';  
$str = $rsa->private_decrypt($str); //用私密钥解密  
echo $str,'</br>';  
//=============================================================  
$str = $rsa->private_encrypt($str); //用丝密钥加密  
echo $str,'</br>';  
$str = $rsa->public_decrypt($str); //用公密钥解密  
echo $str,'</br>';  

 


  • 微信或支付宝

道,可道,非常道;名,可名,非常名。