RSA-2003

PHP RSA加解密类

前言:RSA加密算法是一种非对称加密(不能根据加密算法推算出解密算法)算法。在公开密钥加密和电子商业中RSA被广泛使用。RSA是1977年由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的。当时他们三人都在麻省理工学院工作。RSA就是他们三人姓氏开头字母拼在一起组成的。主要运用了大质数难以分解的特点。

1.使用方法

<?php
$rsa = new RSA('public key abs path','private key abs path');
$encoded = $rsa->encode('hello');

 

2.源码

<?php
class RSA{
	public $path_pubkey_der = '';
	public $path_prvkey_der='';

	protected $sPublicKey;
	protected $publickey;
	
	protected $sPrivateKey;
	protected $privatekey;
	
        /**
         * 构造函数
         * @param type $path_pubkey_der 公钥路径
         * @param type $path_prvkey_der 私钥路径
         */
	public function __construct($path_pubkey_der = '', $path_prvkey_der = '') {
		$this->path_pubkey_der = $path_pubkey_der;
		$this->path_prvkey_der = $path_prvkey_der;
	}

	/**
	 * 转换密钥文件格式
	 *
	 * @param unknown_type $der_data der密钥内容
	 * @return unknown $pem pem密钥内容
	 */
	protected function der2pem($der_data,$type='PUBLIC') {
		$pem = chunk_split(base64_encode($der_data), 64, "\n");
		$pem = "-----BEGIN {$type} KEY-----\n".$pem."-----END {$type} KEY-----\n";
		return $pem;
	}

        /**
         * 加载密钥
         */
	protected function loadKey(){
		if ( empty( $this->sPublicKey ) ){

			if ( is_file( $this->path_pubkey_der ) ){
				$this->sPublicKey = $this->der2pem( @file_get_contents( $this->path_pubkey_der ) );
			}
		}

//		var_dump( $this->sPublicKey );

		if ( empty( $this->publickey ) && !empty( $this->sPublicKey ) ){
			$this->publickey = openssl_pkey_get_public( $this->sPublicKey );
		}
		
		
		//load private key
		if (empty($this->sPrivateKey)) {
			if (is_file($this->path_prvkey_der)) {
				$this->sPrivateKey = $this->der2pem(@file_get_contents($this->path_prvkey_der),'RSA PRIVATE');
			}
		}

		if (empty($this->privatekey) && !empty($this->sPrivateKey)) {
			$this->privatekey = openssl_pkey_get_private($this->sPrivateKey);
		}
		
	}

        /**
         * 解密
         * @param type $encoded 加密的字符串
         * @return boolean
         */
	public function decode( $encoded ){
		$decoded = false;

		if ( empty( $this->publickey ) ){
			$this->loadKey();
		}

		if ( !empty( $this->publickey ) && !empty( $encoded ) ){
			$encoded=  base64_decode($encoded);
				if(openssl_public_decrypt( $encoded, $decoded, $this->publickey )){
					return $decoded;		
				}
		}

		return $decoded;
	}
	
        /**
         * 加密
         * @param type $data 字符串,建议长度限制在117个字符以内
         * @return type
         */
	public function encode($data) {
		$encoded = false;
		
		if(empty($this->privatekey)){
			$this->loadKey();
		}

		if (!empty($this->privatekey) && !empty($data)) {
			if (openssl_private_encrypt($data, $encoded, $this->privatekey)) {
				$encoded = base64_encode($encoded);
				return $encoded;
			}
		}

		return $encoded;
	}
}

 

%1 $ S

发表回复