RSA 加解密的例子,JS加密--php解密

在网上找到一个很好的RSA 加解密的例子:其中JS用的库在 https://github.com/ziyan/javascript-rsa 上能找到(要用到的加解密库文件有jsbn.js jsbn2.js sha1.js rsa.js 记得加上jsbn2.js不然会出错的)完整的例子上面也有,可以下载。下面粘贴一下例子:
login.html

<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Javascript RSA - Login Test</title>
<script type="text/javascript" src="jsbn.js"></script>
<script type="text/javascript" src="rsa.js"></script>
<script type="text/javascript" src="sha1.js"></script>
<script type="text/javascript" src="jsbn2.js"></script>

<script type="text/javascript">
var $pem = "-----BEGIN PUBLIC KEY-----MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMYQWDqtLgDKlQvWzacGeBMQpbicd/uoXAvgLNpFZLM7zuYFDhrYncRsl8LIHK0K3f7e1aFmUVgM4LrKU2WFIw0CAwEAAQ==-----END PUBLIC KEY-----";
var $key = RSA.getPublicKey($pem);
function assemble() {
var password_field = document.getElementById("password");
var data_field = document.getElementById("data");
data_field.value=sha1(password_field.value) + (new Date().getTime());
}
function encrypt() {
var login_field = document.getElementById("login");
var data_field = document.getElementById("data");
login_field.value=RSA.encrypt(data_field.value, $key);
}
</script>

</head>

<body>
<h1>Javascript RSA - Login Test</h1>
This test is an example to perform user login using javascript RSA. <br/>
<ol>
<li>The user type in E-mail as username and a password.</li>
<li>The client-side javascript hashes the password using SHA-1.</li>
<li>The client-side javascript attach a timestamp to the end of the hash.</li>
<li>The client-side javascript encrypt the whole thing with the RSA public key.</li>

<li>The browser submits the encrypted data.</li>
</ol>
<strong>For testing purpose, the credential to login is any E-mail with the password "test".</strong><br/><br/>

<form action="login.php" method="post">
Email:<br/>
<input name="email" type="text" size="40"/><br/>
Password:<br/>
<input id="password" type="password" size="40"/><br/>
<input type="button" onclick="assemble()" value="1. Assemble"/><br/>
<textarea id="data" cols="50" rows="2"></textarea><br/>
<input type="button" onclick="encrypt()" value="2. Encrypt"/><br/>

<textarea id="login" name="login" cols="50" rows="10"></textarea><br/>
<input name="submit" type="submit" value="3. Login" size="10"/>
</form>
</body>

</html>

login.php

login.php
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Javascript RSA - Login Test</title>
</head>

<body>

<?php

define("KEY_PUBLIC", "-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMYQWDqtLgDKlQvWzacGeBMQpbicd/uo
XAvgLNpFZLM7zuYFDhrYncRsl8LIHK0K3f7e1aFmUVgM4LrKU2WFIw0CAwEAAQ==
-----END PUBLIC KEY-----
");

define("KEY_PRIVATE", "-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,2BE9EB9BD7712C2B

FQ9nRtev8hFY+FXkbnH2qBdg7+cD4x759C5c+5PhwWAVccOA4nvtBnE4AUT1bC+H
r/viTPzL5M0vFbAfpOPeUVfuCYXmAxFwcW+pn++UtlNezMtWqZdGPSPc86OqtChE
PjZ5rNBhjTAY7xXX2n+jbZSq8M2LSWyM4gy3Oj8QMnKwdGNWeM/E/4uYyMr5V3Eb
7KveReWJnZ3r3mF7uWJYCjABRzVF8k5sn86FpRn6pLWRHigkpiyNGF7acJMRqaSY
RUIrVf5xclLloUoSuEAe8HSdTH7oxl3vqf8byedqzuWyAxCFWRNr2e+TJ79f1XPJ
m9vLhWhm1BWM3OiB8iw2MkaTx/RCEf31O3cgNG3bcW/uIZrvdV0xRhHsjk0HNFNI
QOEcS73avo2o4ncPJpxLGqg+a0ERtRhFRp0JdgwCxl8=
-----END RSA PRIVATE KEY-----
");

define("KEY_PASSPHRASE", "testkey");
define("TEST_PASSWORD", "test");

function login($email, $login) {
   // decrypt argument
   if(!openssl_private_decrypt($login, $login, openssl_pkey_get_private(KEY_PRIVATE,KEY_PASSPHRASE))) {
      echo "Failed to decrypt message.\n";
      return false;
   }
   // expecting sha1password+timestamp
   if(strlen($login)<44) return false;
   // extract password
   $password = substr($login,0,40);
   // extract stamp, stamp has milliseconds and is bigger than int
   $stamp = substr($login,40);
   // extract timestamp, timestamp is in seconds, and is an int
   $timestamp = substr($stamp,0,strlen($stamp)-3);
   if(!is_numeric($timestamp)) return false;
   // check timestamp
   if(abs(time() - (int)$timestamp) > 300) {
      echo "Timestamp expired. Client and server times may be out of sync.\n";
      return false;
   }
   // construct stamp
   //$stamp = "user.login.".sha1($email).".".$stamp;
   // take a note of the stamp, each unique stamp can only be used once
   //if($memcache->get($stamp) != NULL) return false;
   //$memcache->set($stamp,1,USER_LOGIN_TIMESTAMP_TTL);
   // connect to db and check password
   // check password
   if (pack("H*",$password)!=pack("H*",sha1(TEST_PASSWORD))) {
      echo "Password incorrect.\n";
      return false;
   }
   return true;
}


?>

<h1>Javascript RSA - Login Test</h1>
This test is an example to perform user login using javascript RSA. <br/>
<ol>
<li>Once the encrypted data is received, the server side decrypt using private key.</li>
<li>The message is separated into two parts, the hash and the timestamp.</li>
<li>The timestamp is checked to make sure the request is made in recent time. Set to allow up to 30 second difference.</li>
<li>The timestamp is recorded to make sure no single timestamp is repeated for a user.</li>
<li>The password hash is compared to the hash in the database.</li>
</ol>
For testing purpose, the credential to login is any E-mail with the password "test".<br/>
No database connection is made in this test. A hardcoded check is used. <br/>
Also the duplicate timestamp check is by-passed since it requires the presence of a memcached server.<br/>
The result is displayed:<br/>

<pre>
<?php
   $email = $_REQUEST["email"];
   $login = base64_decode($_REQUEST["login"]);
   if(login($email, $login))
      echo "login succeeded!";
   else
      echo "login failed!";
?>
</pre>
The source code for this php file is available <a href="login.txt">here</a>.
</body>

</html>


另外2个可以参考的例子的链接,都很值得一看:
http://blog.csdn.net/linvo/article/details/5666975
http://stackoverflow.com/questions/610048/rsa-encryption-decryption-compatible-with-javascript-and-php

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Hutool进行RSA加密解密例子: ```java import cn.hutool.crypto.asymmetric.KeyType; import cn.hutool.crypto.asymmetric.RSA; public class RSATest { public static void main(String[] args) { // 生成RSA密钥对 RSA rsa = new RSA(); String publicKey = rsa.getPublicKeyBase64(); String privateKey = rsa.getPrivateKeyBase64(); System.out.println("公钥:" + publicKey); System.out.println("私钥:" + privateKey); // 加密 String data = "Hello, World!"; byte[] encrypt = rsa.encrypt(data.getBytes(), KeyType.PublicKey); String encryptStr = cn.hutool.core.codec.Base64.encode(encrypt); System.out.println("加密后的数据:" + encryptStr); // 解密 byte[] decrypt = rsa.decrypt(cn.hutool.core.codec.Base64.decode(encryptStr), KeyType.PrivateKey); String decryptStr = new String(decrypt); System.out.println("解密后的数据:" + decryptStr); } } ``` 在上面的例子中,我们首先使用`RSA`类生成RSA密钥对,然后使用公钥对数据进行加密,使用私钥对加密后的数据进行解密。在加密解密时,我们需要指定密钥类型(公钥或私钥)。最后,我们将加密解密后的数据进行输出验证。注意,我们在输出加密后的数据时,使用了`cn.hutool.core.codec.Base64.encode`方法将加密后的字节数组转换为Base64字符串,以便更方便地输出和传输。同样,在解密时,我们使用了`cn.hutool.core.codec.Base64.decode`方法将Base64字符串转换为字节数组。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值