首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >openssl_private_decrypt()与来自cryptico.js的密文一起返回false

openssl_private_decrypt()与来自cryptico.js的密文一起返回false
EN

Stack Overflow用户
提问于 2017-04-15 00:35:34
回答 1查看 1.1K关注 0票数 1

我正在服务器上创建一个公钥/私钥,将公钥发送到JavaScript客户机,在该客户机中,它使用cryptico.js库:https://github.com/wwwtyro/cryptico/blob/master/cryptico.js加密用户密码。

代码语言:javascript
复制
$res = openssl_pkey_new(array( 
  'private_key_bits' => 2048,
  'private_key_type' => OPENSSL_KEYTYPE_RSA,
  'digest_alg' => 'sha256'
));

以下是这个较旧的帖子Encrypt with Cryptico.js, Decrypt with OpenSSL的一些建议

代码语言:javascript
复制
//Made Public key compatible with cryptico.js

$detail = openssl_pkey_get_details($res);
$n = base64_encode($detail['rsa']['n']);
$e = bin2hex($detail['rsa']['e']);

$publicKey = "$n|$e";
openssl_pkey_export($res, $privateKey);

file_put_contents("public_key",$publicKey);
file_put_contents("private_key",$privateKey);

按照同一篇文章中的建议,在cryptico.js中做了两次修改

代码语言:javascript
复制
my.publicKeyFromString = function(string)
{
  var tokens = string.split("|");
  var N = my.b64to16(tokens[0]);
  var E = tokens.length > 1 ? tokens[1] : "03";
  var rsa = new RSAKey();
  rsa.setPublic(N, E);
  return rsa
}

my.encrypt = function(plaintext, publickeystring, signingkey)
{
  var cipherblock = "";
  try
  {
    var publickey = my.publicKeyFromString(publickeystring);
    cipherblock += my.b16to64(publickey.encrypt(plaintext));
  }
  catch(err)
  {
    return {status: "Invalid public key"};
  } 
  return {status: "success", cipher: cipherblock};
}

现在在客户端js中:

代码语言:javascript
复制
var publicKey = '<php echo file_get_contents("public_key")?>';
var encrypted = cryptico.encrypt("plain text", publicKey);
var data = 'encrypted_post_var='+encrypted.chiper;

然后我通过AJAX POST发送数据,并验证它是否已被$_POST"encrypted_post_var“成功地接收到。

在php中:

代码语言:javascript
复制
$private = openssl_pkey_get_private(file_get_contents("private_key"));

//!!! THAT is the problem because here openssl_private_decrypt() return FALSE !!!
openssl_private_decrypt(base64_decode($_POST["encrypted_post_var"]), $decrypted, $privateKey); 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-18 10:43:04

解决了

最后,我找到了一种让它发挥作用的方法:)

在my.encrypt()函数中,我更改了这一行:

代码语言:javascript
复制
cipherblock += my.b16to64(publickey.encrypt(plaintext));

代码语言:javascript
复制
cipherblock = publickey.encrypt(plaintext);
//that return the cipherblock (ciphertext) in hex format instead base64

在php中,我改变了这一点:

代码语言:javascript
复制
openssl_private_decrypt(base64_decode($_POST["encrypted_post_var"]), $decrypted, $privateKey);

至:

代码语言:javascript
复制
openssl_private_decrypt(pack('H*',$_POST["encrypted_post_var"]), $decrypted, $privateKey);

现在工作得很好!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43420940

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档