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Psuik 23 th/43qP+1IWTYTv1i967pDnQjXKbnm1dEMvjmS5hi7b/WwNfTi/VdAGLN0nxiHlX 24 4+czjNHA3pCSQ9hCzwIDAQAB 25 -----END PUBLIC KEY-----"; 26 27 28 29 $rsa = new mycrypt($pub,$pri); 30 $encryptContent = $rsa -> encrypt('hankangkang'); 31 echo $encryptContent.'<br>'; 32 $decryptContent = $rsa -> decrypt($encryptContent); 33 echo $decryptContent.'<br>'; 34 35 class mycrypt { 36 37 public $pubkey; 38 public $privkey; 39 40 function __construct($pub,$pri) { 41 $this->pubkey = $pub; 42 $this->privkey = $pri; 43 } 44 45 public function encrypt($data) { 46 if (openssl_public_encrypt($data, $encrypted, $this->pubkey)) 47 $data = base64_encode($encrypted); 48 else 49 throw new Exception('Unable to encrypt data. Perhaps it is bigger than the key size?'); 50 51 return $data; 52 } 53 54 public function decrypt($data) { 55 if (openssl_private_decrypt(base64_decode($data), $decrypted, $this->privkey)) 56 $data = $decrypted; 57 else 58 $data = ''; 59 60 return $data; 61 } 62 63 }