使用公钥加密在Javascript中加密,在PHP中解密 [英] Encrypt in Javascript, decrypt in PHP, using public-key cryptography

查看:177
本文介绍了使用公钥加密在Javascript中加密,在PHP中解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用JavaScript加密,用PHP解密,使用公钥加密。我一直在努力寻找可以实现这一目标的库,但是我遇到了问题。

I'd like to encrypt in JavaScript, decrypt in PHP, using public-key cryptography. I've been trying to find libraries that can accomplish this, but am having issues.

我目前正在寻找 openpgpjs ,但我需要在所有浏览器中提供支持,甚至测试页面也只有列出的支持浏览器(谷歌浏览器)才会出现错误。

I am currently looking at openpgpjs, but I need support in all browsers, and even the test page has errrors on the only listed as supported browser (Google Chrome).

关于最终目标的说明:

TCP连接已受SSL保护。这一保护层的主要目的是防止有意或无意的网络服务器日志记录,崩溃转储等。

在PHP端,一个临时私钥将生成(它将在短时间后过期)。调用者(在Javascript中)负责在新的公钥到期时要求它。私钥到期的原因是为了防止记录加密数据解密,以防存储私钥的服务器稍后被泄露。

On the PHP side, a temporary private key will be generated (it will expire after a short time). The caller (in Javascript) is responsible for asking for a new public key when it expires. The reason for private key expiration is to prevent logged encrypted data decryption, in case the server which stores the private key is later compromised.

服务器受损情况:有人得到他的手对于除数据库服务器之外的所有计算机的备份(由于防火墙而无法访问数据库,即使他找到了用户和密码)。由于加密记录数据的私钥不再存在,攻击者无法做到。

Servers compromised scenario: someone gets his hands on backups for all machines except the database server (and cannot access the database due to firewalling, even if he finds out the user and password). Since the private key which encrypted the logged data no longer exists, there is nothing the attacker can do.

推荐答案

我用过我的登录页面类似的东西;它使用给定的公钥信息(N,e)加密登录凭证,可以用PHP解密。

I've used something similar for my login page; it encrypts login credentials using the given public key information (N, e) which can be decrypted in PHP.

它使用以下文件作为 JSBN

It uses the following files that are part of JSBN:


  • jsbn.js - 使用大整数

  • rsa.js - 仅适用于RSA加密(使用jsbn.js)

  • rng.js - 基本熵收集器

  • prng4.js - ARC4 RNG后端

  • jsbn.js - to work with big integers
  • rsa.js - for RSA encryption only (uses jsbn.js)
  • rng.js - basic entropy collector
  • prng4.js - ARC4 RNG backend

加密数据:

$pk = '-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----';
$kh = openssl_pkey_get_private($pk);
$details = openssl_pkey_get_details($kh);

function to_hex($data)
{
    return strtoupper(bin2hex($data));
}

?>
<script>
var rsa = new RSAKey();
rsa.setPublic('<?php echo to_hex($details['rsa']['n']) ?>', '<?php echo to_hex($details['rsa']['e']) ?>');

// encrypt using RSA
var data = rsa.encrypt('hello world');
</script>

这是解码发送数据的方式:

This is how you would decode the sent data:

$kh = openssl_pkey_get_private($pk);
$details = openssl_pkey_get_details($kh);
// convert data from hexadecimal notation
$data = pack('H*', $data);
if (openssl_private_decrypt($data, $r, $kh)) {
   echo $r;
}

这篇关于使用公钥加密在Javascript中加密,在PHP中解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆