PHP RSA加密解密

Android或IOS需要的公鈅格式可能需要转换。

<?php
class Rsa {
	private $private;
	private $public;
	function __construct($private, $public = null) {
		$this->private = $private;
		$this->public = $public;
	}
	private function getPrivateKey() {
		return openssl_pkey_get_private ( $this->private );
	}
	private function getPublicKey() {
		return openssl_pkey_get_public ( $this->public );
	}
	function publicEncrypt($data) {
		if (! is_string ( $data )) {
			user_error ( 'data must be string', E_USER_WARNING );
			return;
		}
		return openssl_public_encrypt ( $data, $encrypted, $this->getPublicKey () ) ? base64_encode ( $encrypted ) : null;
	}
	function publicDecrypt($encrypted) {
		if (! is_string ( $encrypted )) {
			user_error ( 'encrypted must be string', E_USER_WARNING );
			return;
		}
		return (openssl_public_decrypt ( base64_decode ( $encrypted ), $decrypted, $this->getPublicKey () )) ? $decrypted : null;
	}
	function privateEncrypt($data) {
		if (! is_string ( $data )) {
			user_error ( 'data must be string', E_USER_WARNING );
			return;
		}
		return openssl_private_encrypt ( $data, $encrypted, $this->getPrivateKey () ) ? base64_encode ( $encrypted ) : null;
	}
	function privateDecrypt($encrypted) {
		if (! is_string ( $encrypted )) {
			user_error ( 'encrypted must be string', E_USER_WARNING );
			return;
		}
		return (openssl_private_decrypt ( base64_decode ( $encrypted ), $decrypted, $this->getPrivateKey () )) ? $decrypted : null;
	}
}

base64通过http传输的时候需要处理一下,$data = rawurldecode ( urlencode ( $_GET['data'] ) );

下载:Rsa

发表评论

电子邮件地址不会被公开。

*