JavaScript 与 PHP 进行 RSA 加密解密实例

RSA 即“非对称加密算法”。它有3个特征: 

  1. 乙方生成两把密钥(公钥和私钥)。公钥是公开的,任何人都可以获得,私钥则是保密的。
  2. 甲方获取乙方的公钥,然后用它对信息加密。
  3. 乙方得到加密后的信息,用私钥解密。
在开发应用的时候,你可能会碰到这样的需求:密码不能够明文传输,又无法用 HTTPS 协议。这时就可以用到 RSA 来解决这个需求了。
以下是 JAVASCRIPT 调用 RSA 源码:
var public_key="00b0c2732193eebde5b2e278736a22977a5ee1bb99bea18c0681ad97484b4c7f681e963348eb80667b954534293b0a6cbe2f9651fc98c9ee833f343e719c97c670ead8bec704282f94d9873e083cfd41554f356f00aea38d2b07551733541b64790c2c8f400486fd662a3e95fd5edd2acf4d59ca97fad65cc59b8d10cbc5430c53";
var public_length="10001";

var rsa = new RSAKey();
rsa.setPublic(public_key, public_length);	
var password = $.trim($('#q_login_tab').find('input[name="password"]').val());
password = rsa.encrypt(password);
 
我们可以通过浏览器开发人员工具查看密码已经加密。


 
再来看 PHP 是如何调用 RSA 算法的。
<?php
require_once 'rsa.php';

function convert($hexString) {
	$hexLenght = strlen ( $hexString );
	// only hex numbers is allowed 
	if ($hexLenght % 2 != 0 || preg_match ( "/[^\da-fA-F]/", $hexString ))
		return false;
	$binString = '';
	for($x = 1; $x <= $hexLenght / 2; $x ++) {
		$binString .= chr ( hexdec ( substr ( $hexString, 2 * $x - 2, 2 ) ) );
	}
	
	return $binString;
}
/**
 * RSA 解密
 *
 */
function decryptPassword($password) {
	$modulus = '124124790696783899579957666732205416556275207289308772677367395397704314099727565633927507139389670490184904760526156031441045563225987129220634807383637837918320623518532877734472159024203477820731033762885040862183213160281165618500092483026873487507336293388981515466164416989192069833140532570993394388051.0000000000';
	$private = '59940207454900542501281722336097731406274284149290386158861762508911700758780200454438527029729836453810395133453343700246367853044479311924174899432036400630350527132581124575735909908195078492323048176864577497230467497768502277772070557874686662727818507841304646138785432507752788647631021854537869399041.0000000000';
	$public = "65537";
	$keylength = "1024";
	$encrypted = convert ( $password ); //hex data to bin data

	//php encrypt create  
	//$encrypted = rsa_encrypt("vzxcvz bdxf", $public, $modulus, $keylength);
	//$str= bin2hex($encrypted);//bin data to hex data 
	//$str = $_POST['ciphertext'];
	//echo $str."
";
	
	return rsa_decrypt ( $encrypted, $private, $modulus, $keylength );
}

$password = decryptPassword($_POST['password']);

?>
 
这样,就可以解密出明文的密码了。这里附上 RSA源码,有兴趣的童鞋可以下载,在自己的服务器运行。 https://yunpan.cn/cSfKMpfffVFzu  访问密码 1fe5

猜你喜欢

转载自wangzq-phper.iteye.com/blog/2298158