Encrypt with Cryptico.js, Decrypt with OpenSSL

2019-02-11 06:17发布

问题:

I am creating a public/private key on the server, sending the key to the JavaScript client where it encrypts a users password. The client sends the password to the server, and the server uses the private key to decrypt it, but the password is coming back null. I have verified all values supporting the situation are correct, so it's something with the encryption/decryption specifically. Where am I going wrong?

Possibly, is cryptico.js not compatible with php openssl?

Library Info:

https://github.com/wwwtyro/cryptico

http://www.php.net/manual/en/function.openssl-pkey-new.php

Here are relevant code snippets:

PHP - create public/private key

$config = array(
    "digest_alg" => "sha512",
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
);

// Create the private and public key
$res = openssl_pkey_new($config);

// Extract the private key from $res to $privateKey
openssl_pkey_export($res, $privateKey);

// Extract the public key from $res to $publicKey
$publicKey = openssl_pkey_get_details($res);
$publicKey = $publicKey["key"];

JavaScript - Client encrypts data with public key.

var xhr = new XMLHttpRequest();
var data = new FormData();
xhr.open('POST', '/signUp2.php');
data.append('user', User);

var encryptedPassword = cryptico.encrypt(password, localStorage["publicKey"]);
data.append('password', encryptedPassword.cipher);

xhr.onreadystatechange = function()
{
    if(xhr.readyState == 4 && xhr.status == 200)
    {
        var jsonArray = JSON.parse(xhr.responseText);

        if(jsonArray[0] == "0")
        {
            alert("Account created.  You may now sign in.");
        }
        else
            alert("Error Code: " + jsonArray[0]);
    }
}
xhr.send(data);

PHP - Server recieves encrypted password and attemps to decrypt unsuccessfully

openssl_private_decrypt($encryptedPassword, $decryptedPassword, $row[1]);

回答1:

cryptico.js could work with openssl, but we have to modify it a bit.

it don't directly recognize the public key in pem format (which openssl use). we have to extract the 'n' and 'e' part of a public key in php side:

$key = openssl_pkey_new(array( 
  'private_key_bits' => 1024,
  'private_key_type' => OPENSSL_KEYTYPE_RSA,
  'digest_alg' => 'sha256'
));

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

also, cryptico.js hardcoded the 'e' part of a public key (see definition of publicKeyFromString in api.js), so we need to fix this:

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
}

now we are able to encrypt strings:

var publicKey = "{$n}|{$e}",
    encrypted = cryptico.encrypt("plain text", publicKey);

job is not finished yet. the result of cryptico.encrypt is NOT simply encrypted by RSA. indeed, it was combined of two parts: an aes key encrypted by RSA, and the cipher of the plain text encrypted with that aes key by AES. if we only need RSA, we could modify my.encrypt:

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};
}

now we are able to decrypt the cipher with openssl:

$private = openssl_pkey_get_private("YOUR PRIVATE KEY STRING IN PEM");
// $encrypted is the result of cryptico.encrypt() in javascript side
openssl_private_decrypt(base64_decode($encrypted), $decrypted, $private);
// now $decrypted holds the decrypted plain text