一. openssl
它集成了眾多密碼算法及實(shí)用工具
rsa加密流程肠骆;(今天只講眾多加密方式中的一種)
- 在當(dāng)前文件夾下生成一個(gè)包含 "公鑰"和"私鑰" 兩部分內(nèi)容的文本文件; 命名test.key
[root@iZ28pw7sv4qZ openssl]#openssl genrsa -out test.key 1024
2.將這個(gè)文本文件中的“公鑰”提取出來(lái): 命名test_pub.key
[root@iZ28pw7sv4qZ openssl]#openssl rsa -in test.key -pubout -out test_pub.key
3.創(chuàng)建一個(gè)hello.txt的文本文件屡穗,然后利用此前生成的公鑰加密文件;
[root@iZ28pw7sv4qZ openssl]#echo "1234561122" > ./hello.txt
[root@iZ28pw7sv4qZ openssl]#openssl rsautl -encrypt -in hello.txt -inkey test_pub.key -pubin -out hello.en.txt
4.解密文件
[root@iZ28pw7sv4qZ openssl]#openssl rsautl -decrypt -in hello.en.txt -inkey test.key -out hello.de.txt
5.解析后的結(jié)果
[root@iZ28pw7sv4qZ openssl]# cat hello.de.txt
二. js加密php解密
前端代碼:
<!DOCTYPE html>
<html>
<head>
// 引入 jquery 和 jsencrypt.js
<script src="./jquery.min.js"></script>
<script src="./jsencrypt.js"></script>
<script type="text/javascript">
$(function () {
var encrypt = new JSEncrypt();
encrypt.setPublicKey('MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC0Llg1bVZhnyslfezwfeOkvnXWq59bDtmQyHvxkP/38Fw8QQXBfROCgzGc+Te6pOPl6Ye+vQ1rAnisBaP3rMk40i3OpallzVkuwRKydek3V9ufPpZEEH4eBgInMSDiMsggTWxcI/Lvag6eHjkSc67RTrj96oxj0ipVRqjxW4X6HQIDAQAB');//設(shè)置公有key
var data = encrypt.encrypt("需要機(jī)密的內(nèi)容");
console.log(data);
$("#btn").click(function () {
$.ajax({
url: '/openssl/index.php',
data: "password=" + encodeURI(data).replace(/\+/g, '%2B'), //+號(hào)的處理:因?yàn)閿?shù)據(jù)在網(wǎng)絡(luò)上傳輸時(shí),非字母數(shù)字字符都將被替換成百分號(hào)(%)后跟兩位十六進(jìn)制數(shù)唉工,而base64編碼在傳輸?shù)胶蠖说臅r(shí)候荸频,+會(huì)變成空格,因此先替換掉。后端再替換回來(lái)
type: 'post',
success: function (msg) {
alert(msg);
}
});
});
});
</script>
</head>
<body>
<div class="main">
<input type="button" id="btn" value="點(diǎn)我" />
<hr/>
注意+好的處理
</div>
</body>
</html>
PHP代碼:
<?php
class Index{
public function index
{
if(isset($_POST['password']))
{
$txt = $this->decodeing($_POST['password']);
die('解密字符串:'.$txt);
}
}
/**
* 公鑰加密
*
* @param string 明文
* @return string 密文(base64編碼)
*/
public function encodeing($sourcestr)
{
$key_content = file_get_contents('./_test_public.key');
$pubkeyid = openssl_get_publickey($key_content);
if (openssl_public_encrypt($sourcestr, $crypttext, $pubkeyid))
{
return base64_encode("".$crypttext);
}
}
/**
* 私鑰解密
*
* @param string 密文(二進(jìn)制格式且base64編碼)
* @param string 密文是否來(lái)源于JS的RSA加密
* @return string 明文
*/
public function decodeing($crypttext)
{
$key_content = file_get_contents('./_test.key');
$prikeyid = openssl_get_privatekey($key_content);
$crypttext = base64_decode($crypttext);
if (openssl_private_decrypt($crypttext, $sourcestr, $prikeyid, OPENSSL_PKCS1_PADDING))
{
return "".$sourcestr;
}
return ;
}
}
下載地址: http://files.cnblogs.com/files/sixiong/openssl.zip
源自:https://www.cnblogs.com/sixiong/p/5885111.html
源自:https://www.cnblogs.com/chrdai/p/8566463.html
謝謝兩位博主亡鼠!