EzDevInfo.com

cryptico

An easy-to-use encryption system utilizing RSA and AES for javascript. Cryptico by wwwtyro

SSL Over Javascript

I've seen a few similar questions that don't quite seem to address my exact use case, and I THINK I've figured out the answer, but I'm a total noob when it comes to security, RSA, and pretty much everything associated with it. I have a basic familiarity with the concepts, but all of the actual implementations I've done up to this point were all about editing someone else's code rather than generating my own. Anyway, here's where I am:

I know that Javascript is an inherently bad place to do encryption. Someone could Man-in-the-Middle your response and mangle the JS so you'll end up sending unencrypted data over the wire. It SHOULD be done via an HTTPS SSL/TLS connection, but that kind of hosting costs money and so do the official signed certificates that should realistically go with the connection.

That being said, I think the way I'm going to do this circumvents the Man-in-the-Middle weakness of JS encryption by virtue of the fact that I'm only ever encrypting one thing (a password hash) for one RESTful service call and then only using that password hash to sign requests from the client in order to authenticate them as coming from the user the requests claim. This means the JS is only responsible for encrypting a password hash once at user account creation and if the server cannot decode that cipher then it knows it's been had.

I'm also going to save some client information, in particular the $_SERVER['REMOTE_ADDR'] to guarantee that someone doesn't M-i-t-M the registration exchange itself.

I'm using PHP's openssl_pkey_ functions to generate an asymmetric key, and the Cryptico library on the client side. My plan is for the user to send a "pre-registration" request to the REST service, which will cause the server to generate a key, store the private key and the client information in a database indexed by the email address, and then respond with the public key.

The client would then encrypt the user's password hash using the public key and send it to the REST service as another request type to complete the registration. The server would decrypt and save the password hash, invalidate the client information and the private key so no further registrations could be conducted using that information, and then respond with a 200 status code.

To login, a user would type in their email address and password, the password would be hashed as during registration, appended to the a request body, and hashed again to sign a request to a login endpoint which would try to append the stored hash to the request body and hash it to validate the signature against the one in the request and so authenticate the user. Further data requests to the service would follow the same authentication process.

Am I missing any glaring holes? Is is possible to spoof the $_SERVER['REMOTE_ADDR'] value to something specific? I don't need the IP address to be accurate or the same as when the user logs in, I just need to know that the same machine that 'pre-registered' and got a public key followed up and completed the registration instead of a hijacker completing the registration for them using a snooped public key. Of course, I guess if they can do that, they've hijacked the account beyond recovery at creation and the legitimate user wouldn't be able to complete the registration with their own password, which is ok too.

Bottom line, can someone still hack my service unless I fork out for a real SSL host? Did I skirt around Javascript's weaknesses as an encryption tool?


As I write and debug my code, I'll post it here if anyone wants to use it. Please let me know if I'm leaving my site open to any kind of attacks.

These are the functions that validate client requests against the hash in the headers, generate the private key, save it to the database, respond with the public key, and decrypt and check the password hash.

        public function validate($requestBody = '',$signature = '',$url = '',$timestamp = '') {
            if (is_array($requestBody)) {
                if (empty($requestBody['signature'])) { return false; }
                if (empty($requestBody['timestamp'])) { return false; }
                if ($requestBody['requestBody'] === null) { return false; }

                $signature = $requestBody['signature'];
                $timestamp = $requestBody['timestamp'];
                $requestBody = $requestBody['requestBody'];
            }

            if (($requestBody === null) || empty($signature) || empty($timestamp)) { return false; }

            $user = $this->get();

            if (count($user) !== 1 || empty($user)) { return false; }
            $user = $user[0];

            if ($signature !== md5("{$user['pwHash']}:{$this->primaryKey}:$requestBody:$url:$timestamp")) { return false; }

            User::$isAuthenticated = $this->primaryKey;
            return $requestBody;
        }

        public function register($emailAddress = '',$cipher = '') {
            if (is_array($emailAddress)) {
                if (empty($emailAddress['cipher'])) { return false; }
                if (empty($emailAddress['email'])) { return false; }

                $cipher = $emailAddress['cipher'];
                $emailAddress = $emailAddress['email'];
            }

            if (empty($emailAddress) || empty($cipher)) { return false; }

            $this->primaryKey = $emailAddress;
            $user = $this->get();

            if (count($user) !== 1 || empty($user)) { return false; }
            $user = $user[0];

            if (!openssl_private_decrypt(base64_decode($cipher),$user['pwHash'],$user['privateKey'])) { return false; }
            if (md5($user['pwHash'].":/api/preRegister") !== $user['session']) { return false; }

            $user['session'] = 0;
            if ($this->put($user) !== 1) { return false; }

            $this->primaryKey = $emailAddress;
            User::$isAuthenticated = $this->primaryKey;
            return $this->getProfile();
        }

        public function preRegister($emailAddress = '',$signature = '') {
            if (is_array($emailAddress)) {
                if (empty($emailAddress['signature'])) { return false; }
                if (empty($emailAddress['email'])) { return false; }

                $signature = $emailAddress['signature'];
                $emailAddress = $emailAddress['email'];
            }

            if (empty($emailAddress) || empty($signature)) { return false; }

            $this->primaryKey = $emailAddress;

            $response = $this->makeUserKey($signature);
            if (empty($response)) { return false; }

            $response['emailAddress'] = $emailAddress;
            return $response;
        }

        private function makeUserKey($signature = '') {
            if (empty($signature)) { return false; }

            $config = array();
            $config['digest_alg'] = 'sha256';
            $config['private_key_bits'] = 1024;
            $config['private_key_type'] = OPENSSL_KEYTYPE_RSA;

            $key = openssl_pkey_new($config);
            if (!openssl_pkey_export($key,$privateKey)) { return false; }
            if (!$keyDetails = openssl_pkey_get_details($key)) { return false; }

            $keyData = array();
            $keyData['publicKey'] = $keyDetails['key'];
            $keyData['privateKey'] = $privateKey;
            $keyData['session'] = $signature;

            if (!$this->post($keyData)) { return false; }

            $publicKey = openssl_get_publickey($keyData['publicKey']);
            $publicKeyHash = md5($keyData['publicKey']);

            if (!openssl_sign($publicKeyHash,$signedKey,$privateKey)) { return false; }
            if (openssl_verify($publicKeyHash,$signedKey,$publicKey) !== 1) { return false; }

            $keyData['signedKey'] = base64_encode($signedKey);
            $keyData['rsa'] = base64_encode($keyDetails['rsa']['n']).'|'.bin2hex($keyDetails['rsa']['e']);
            unset($keyData['privateKey']);
            unset($keyData['session']);

            return $keyData;
        }

Source: (StackOverflow)

RSA encrypt/decrypt with phpseclib and Cryptico

I'm desperately searching for a way to encrypt/decrypt data between javascript using Cryptico and decrypt/encrypt using phpseclib.


Source: (StackOverflow)

Advertisements

AES/RSA Encryption/Decryption in JavaScript

I'm using this library to do RSA key gen, encryption and decryption. Everything was working pretty fine, then I decided to implement a hybrid cryptographic scheme using this library for AES. I got the snippet for AES crypt/decrypt from cryptico library (same as the AES library linked), and tried to mix it with the RSA library. I tried to follow the exact same steps as cryptico does to encrypt and decrypt in AES algorithm, but something is getting wrong. I saw that the same key used for encryption, is sent for decryption, and the functions are just copy&paste from cryptico (and right there it works!!). For some unknown reason when I click to decrypt, I get wrong result. Here's my entire HTML/JS code for the job:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>JavaScript RSA Cryptography Demo</title>
  </head>

<script language="JavaScript" type="text/javascript" src="jsbn.js"></script>
<script language="JavaScript" type="text/javascript" src="jsbn2.js"></script>
<script language="JavaScript" type="text/javascript" src="prng4.js"></script>
<script language="JavaScript" type="text/javascript" src="rng.js"></script>
<script language="JavaScript" type="text/javascript" src="rsa.js"></script>
<script language="JavaScript" type="text/javascript" src="rsa2.js"></script>
<script language="JavaScript" type="text/javascript" src="rsasync.js"></script>
<script language="JavaScript" type="text/javascript" src="base64.js"></script>
<script language="JavaScript" type="text/javascript" src="aes.js"></script>
<script language="JavaScript">
<!--
aes.Init();

function genRandom() {
    var key = new Array(32);
    var r = new SecureRandom();
    r.nextBytes(key);
    return key;
}

function bytes2string(bytes) {
    var string = "";
    for(var i = 0; i < bytes.length; i++)
    {
        string += String.fromCharCode(bytes[i]);
    }   
    return string;
}

function string2bytes(string)
    {
        var bytes = new Array();
        for(var i = 0; i < string.length; i++) 
        {
            bytes.push(string.charCodeAt(i));
        }
        return bytes;
    }

function blockIV()
    {
        var r = new SecureRandom();
        var IV = new Array(16);
        r.nextBytes(IV);
        return IV;
    }

function pad16(bytes)
    {
        var newBytes = bytes.slice(0);
        var padding = (16 - (bytes.length % 16)) % 16;
        for(i = bytes.length; i < bytes.length + padding; i++)
        {
            newBytes.push(0);
        }
        return newBytes;
    }

function depad(bytes)
    {
        var newBytes = bytes.slice(0);
        while(newBytes[newBytes.length - 1] == 0)
        {
            newBytes = newBytes.slice(0, newBytes.length - 1);
        }
        return newBytes;
    }

function blockXOR(a, b)
    {
        var xor = new Array(16);
        for(var i = 0; i < 16; i++)
        {
            xor[i] = a[i] ^ b[i];
        }
        return xor;
    }

function encryptAESCBC(plaintext, key)
    {
        var exkey = key.slice(0);
        aes.ExpandKey(exkey);
        var blocks = string2bytes(plaintext);
        blocks = pad16(blocks);
        var encryptedBlocks = blockIV();
        for(var i = 0; i < blocks.length/16; i++)
        {
            var tempBlock = blocks.slice(i * 16, i * 16 + 16);
            var prevBlock = encryptedBlocks.slice((i) * 16, (i) * 16 + 16);
            tempBlock = blockXOR(prevBlock, tempBlock);
            aes.Encrypt(tempBlock, exkey);
            encryptedBlocks = encryptedBlocks.concat(tempBlock);
        }
        var ciphertext = bytes2string(encryptedBlocks);
        return b256to64(ciphertext)
    }

function decryptAESCBC(encryptedText, key)
    {
        var exkey = key.slice(0);
        aes.ExpandKey(exkey);
        var encryptedText = b64to256(encryptedText);
        var encryptedBlocks = string2bytes(encryptedText);
        var decryptedBlocks = new Array();
        for(var i = 1; i < encryptedBlocks.length/16; i++)
        {
            var tempBlock = encryptedBlocks.slice(i * 16, i * 16 + 16);
            var prevBlock = encryptedBlocks.slice((i-1) * 16, (i-1) * 16 + 16);
            aes.Decrypt(tempBlock, exkey);
            tempBlock = blockXOR(prevBlock, tempBlock);
            decryptedBlocks = decryptedBlocks.concat(tempBlock);
        }
        decryptedBlocks = depad(decryptedBlocks);
        return bytes2string(decryptedBlocks);
    }

function do_status(s) {
  document.rsatest.status.value = s;
}
function do_init() {
  if(document.rsatest.n.value.length == 0) set_1024f4();
}
function do_encrypt() {
  var before = new Date();
  var rsa = new RSAKey();
  var cipherblock = "";
  rsa.setPublic(document.rsatest.n.value, document.rsatest.e.value);
  var AESKey = bytes2string(genRandom());
  document.rsatest.aeskey.value = AESKey;
  cipherblock += hex2b64(rsa.encrypt(AESKey)) + "?";
  //var res = hex2b64(rsa.encrypt(document.rsatest.plaintext.value));
  cipherblock += encryptAESCBC(document.rsatest.plaintext.value, AESKey);
  var after = new Date();
  if(cipherblock) {
    document.rsatest.ciphertext.value = linebrk(cipherblock, 64);
    document.rsatest.decrypted.value = "";
    do_status("Encryption Time: " + (after - before) + "ms");
  }
}

function do_decrypt() {
  do_status("Decrypting...");
  var before = new Date();
  var rsa = new RSAKey();
  var dr = document.rsatest;
  rsa.setPrivate(dr.n.value, dr.e.value, dr.d.value);
  if(document.rsatest.ciphertext.value.length == 0) {
    do_status("No Ciphertext - encrypt something first");
    return;
  }
  var ciphertext = document.rsatest.ciphertext.value;
  var cipherblock = ciphertext.split("?");
  var AESKey = rsa.decrypt(b64tohex(cipherblock[0]));
  AESKey = string2bytes(AESKey);
  var plaintext = decryptAESCBC(cipherblock[1], AESKey);
  document.rsatest.decrypted.value = plaintext;
  /*var res = rsa.decrypt(b64tohex(document.rsatest.ciphertext.value));
  var after = new Date();
  if(res == null) {
    document.rsatest.decrypted.value = "*** Invalid Ciphertext ***";
    do_status("Decryption failed");
  }
  else {
    document.rsatest.decrypted.value = res;
    do_status("Decryption Time: " + (after - before) + "ms");
  }*/
}
function do_genrsa() {
  var before = new Date();
  var rsa = new RSAKey();
  var dr = document.rsatest;
  do_status("Generating RSA Key...");
  //rsa.generate(parseInt(dr.bits.value),dr.e.value);
  rsa.generateAsync(parseInt(dr.bits.value), dr.e.value, function(){
  dr.n.value = linebrk(rsa.n.toString(16),64);
  dr.d.value = linebrk(rsa.d.toString(16),64);
  dr.p.value = linebrk(rsa.p.toString(16),64);
  dr.q.value = linebrk(rsa.q.toString(16),64);
  dr.dmp1.value = linebrk(rsa.dmp1.toString(16),64);
  dr.dmq1.value = linebrk(rsa.dmq1.toString(16),64);
  dr.coeff.value = linebrk(rsa.coeff.toString(16),64);
  var after = new Date();
  do_status("Key Generation Time: " + (after - before) + "ms");     
});
}
//-->
</script>

  <body onLoad='do_init();'>
    <h1>JavaScript RSA Cryptography Demo</h1>

<form name="rsatest" onSubmit='do_encrypt();return false;'>
Plaintext (string):<br>
<input name="plaintext" type="text" value="test" size=60><br>
<input type="button" value="encrypt" onClick="do_encrypt();"><p>
AES Random-Key:<br>
<textarea name="aeskey" rows=4 cols=70></textarea><br>
Ciphertext (hex):<br>
<textarea name="ciphertext" rows=4 cols=70></textarea><br>
<input type="button" value="decrypt" onClick="do_decrypt();"><p>
Decrypted Plaintext (string):<br>
<input name="decrypted" type="text" size=60><p>
Status:<br>
<input name="status" type="text" size=60><p>
<hr>
<h2>RSA private key</h2><p>
<input type="button" value="1024 bit" onClick='set_1024f4();'>
<input type="button" value="1024 bit (e=3)" onClick='set_1024e3();'>
<input type="button" value="512 bit" onClick='set_512f4();'>
<input type="button" value="512 bit (e=3)" onClick='set_512e3();'>
&nbsp; <input type="button" value="Generate" onClick='do_genrsa();'>
bits = <input name="bits" type="text" value="512" size=10>
<p>
Modulus (hex):<br>
<textarea name="n" type="text" rows=4 cols=70></textarea><p>
Public exponent (hex, F4=0x10001):<br>
<input name="e" type="text" value="3" size=20><p>
Private exponent (hex):<br>
<textarea name="d" type="text" rows=4 cols=70></textarea><p>
P (hex):<br>
<textarea name="p" type="text" rows=2 cols=70></textarea><p>
Q (hex):<br>
<textarea name="q" type="text" rows=2 cols=70></textarea><p>
D mod (P-1) (hex):<br>
<textarea name="dmp1" type="text" rows=2 cols=70></textarea><p>
D mod (Q-1) (hex):<br>
<textarea name="dmq1" type="text" rows=2 cols=70></textarea><p>
1/Q mod P (hex):<br>
<textarea name="coeff" type="text" rows=2 cols=70></textarea>
</form>
    <hr>
    <address><a rel='nofollow' href="mailto:tom@arcot.com">Tom Wu</a></address>
<!-- Created: Sun May  4 19:00:47 PDT 2003 -->
<!-- hhmts start -->
Last modified: Mon Jun 23 16:07:16 PDT 2003
<!-- hhmts end -->
  </body>
</html>

I can't understand how that's possible, because as I said, I'm sure the same key used to crypt, is used to decrypt, and the functions for AES crypt/decrypt are just copy&paste from something that works in another library. Remembering that the RSA part (key gen, crypt and decrypt) were working fine. Someone have a clue about what's going on?


Source: (StackOverflow)

practical use of cryptico.js

Cryptico seems like a super slick RSA encryption library.

cryptico.wwwtyro.net

In regards to JavaScript applications, suppose I want to send data to the client, have them do something to the data, and pass it back. How can I use RSA to ensure that the data clients send back to the server is not tampered with? Since JavaScript is easily reverse-engineered, is there any practical client-side application of cryptico?


Source: (StackOverflow)

cryptico.js encrypted message, must decrypt in C#

I need to be able to decrypt a string on the server using C#, but the string was encrypted using public key encryption with cryptico.js on the client. For details, see context at the end.

Cryptico gives me a private RSA key like this (note - 'like' this - I created a new one for this question):

Array ( [n] => 8029845567507477803775928519657066509146751167600087041355508603090505634905205233922950527978886894355290423984597739819216469551137046641801207199138209 [e] => 3 [d] => 5353230378338318535850619013104711006097834111733391360903672402060337089936682996269976597251251223844095913209399106464214877696419418951728015128013411 [p] => 102067954277225510613941189336789903269738979633396754230261162567549753196947 [q] => 78671563708406591396117399809764267229341143260756252277657051641634753921147 [dmp1] => 68045302851483673742627459557859935513159319755597836153507441711699835464631 [dmq1] => 52447709138937727597411599873176178152894095507170834851771367761089835947431 [coeff] => 26458340158787140383846156526777567128582042036682248240414722856369310516021 

...plus a bunch of methods.

I am trying to decrypt it thusly:

                RSAParameters parameters = new RSAParameters();

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

            parameters.Exponent = encoding.GetBytes("3");

            //dmp1
            parameters.DP =
                encoding.GetBytes("68045302851483673742627459557859935513159319755597836153507441711699835464631");

            //dmq1
            parameters.DQ =
                encoding.GetBytes("52447709138937727597411599873176178152894095507170834851771367761089835947431");

            //d
            parameters.D =
                encoding.GetBytes(
                    "5353230378338318535850619013104711006097834111733391360903672402060337089936682996269976597251251223844095913209399106464214877696419418951728015128013411");

            //p
            parameters.P =
                encoding.GetBytes("102067954277225510613941189336789903269738979633396754230261162567549753196947");

            //q
            parameters.Q =
                encoding.GetBytes("78671563708406591396117399809764267229341143260756252277657051641634753921147");

            //n
            parameters.InverseQ =
                encoding.GetBytes(
                    "8029845567507477803775928519657066509146751167600087041355508603090505634905205233922950527978886894355290423984597739819216469551137046641801207199138209");

            //coeff
            parameters.Modulus =
                encoding.GetBytes("26458340158787140383846156526777567128582042036682248240414722856369310516021");

            RSA rsa = new RSACryptoServiceProvider();
            rsa.ImportParameters(parameters);

            var decryptThis = encoding.GetBytes(ciphertext);

            var result = rsa.DecryptValue(decryptThis);

            resultString = encoding.GetString(result);

But this chucks the Exception 'Bad data'.

Has anyone more experienced with C# got any ideas where I'm going wrong?

Thanks,

G


Details of context: I am attempting to implement a password strength checking function on both the client and server side of an app, but using only code on the server side. To achieve this on the client side, I want to send the putative password to the server, judge its strength, and then return a score which is displayed on the client. This means I only have to maintain password strength checking code on the server. As an extra security measure, I am encrypting the putative password using the cryptico.js library before sending it to the server to be judged.


Source: (StackOverflow)

Encrypt with Cryptico.js, Decrypt with OpenSSL

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]);

Source: (StackOverflow)

Is It Possible To Use RSA encryption instead of SSL in Web App when POSTing?

Let's say I want to build an app in which I don't want to register or can't get an SSL certificate (whatever the reason).

I was wondering if it is possible to get security benefits of SSL by using RSA instead.

Im using the CrypticoJS library - https://github.com/wwwtyro/cryptico)

For example lets say when a user POSTS info to my App. I would do the following:

1) Have RSA private key on server, and give each client an RSA public Key.

2) On Client: Encrypt data with RSA PublicKey before POST, and POST Encrypted Data

3) On Server: Decrypt POST data with Private Key.

4) On server: Save Decrypted Data to DB

The goal is to prevent my user's sensitive info and passwords from being hacked. I know I wont get the green 'Trust' banner when people visit my app, but my User's security is a priority. Please let me know if this is possible. Thanks.


Source: (StackOverflow)

Save RSA Key object from Cryptico.js

I'm struggling to discover how to transform an javascript object, into some variable (array?) and save it with a code like:

function onDownload() {
    document.location = 'data:Application/octet-stream,' +
                         encodeURIComponent(RsaKey);
}

Why?

The library cryptico (documentation: github) gives-me an easy to use RSA interface. But my nightmare came when the generated key pair, is an object. I don't know how to export this object from the client's browser, to a file, for later using. The public part of the key, can be converted in string, by the function

publicKeyString

But the private part, is inside the object. I read about the RSA algorithm and saw that the "d" is what matters in the private key, and I have the "d" in the key gen function, inside the rsa.js

        this.d = ee.modInverse(phi);

I tried to get this value and put into a string, but didn't worked. Don't know what else to do. Appreciate any help.


Source: (StackOverflow)

How to verify with PHP signature genrerated by cryptico.js

I try to sign messages in javascript before sending to a PHP application. The PHP application must check the signature to be sure it's not false.

In javascript I use cryptico.js.

This is the js function for signing messages

var sign = function(passphrase, text) {
    signingkey = cryptico.generateRSAKey(passphrase, 2048);
    signString = cryptico.b16to64(signingkey.signString(text, "sha256"));
    return signString;
}

This is the function for getting the public key:

var getPublicKey = function(passphrase) {
 var rsaKey = cryptico.generateRSAKey(passphrase, 2048);
 return = cryptico.publicKeyString(rsaKey);
}

For example, for the message "message" and the passphrase "test2" the public key and signature are

qH/J3/gvF/h5U02uPyC9Qzn/hHEV5DzB9nFfqk5zbQqHdInVe4sfL+npa+4fjLGrBU30Iuvcr+o9paEjzpH5dY48cq6JHqz1RyJ0CQIc2Jr5+sS4eL1ZIjxWlyN1pKMR+4aE2rlDAad56Ad1cytiaHuVvyK/gdtbKiuGroSQhJ1EVfZ60m3NIqnqmpi5Zdsnmzny4VH/d66BcGXxGaGaUaqFn0WTypuwIMZMMtzZEK7peKoaW4H4rfkfdrKcD8AaT+z9v5lLGkTl0NcZZ4LN9sSUzsHNfyAFK6cSXo/73z0tDAlGb5K+yWV6UHoYW1rcoIsxlNRZM6/6FYgMXbbfow==

XbF4O6v6oadEQGtdpQ7d54Q2JB9/ZEXEUH3S1FMn4E/PSqk7HLXjG4tNfuiUBa5eS8kYV49gwC8Yr+mn6YUAHt+K9lHPSsmltWoiHNOaas4aqai9nlyeft4TYYhP+GYbQfw+3n2TcO39s6M0vw0m0a8AX9JfF02JwCUhP4bu4dzG6Bl5dj000TbUkric14Jyurp8OHmmMvKW62TvXPhNOW39+wS1Qkfn9Bxmzi8UEVSVe3wP45JWZNgmgeGnpubDhD05FJEDErfVtZ/DRKD81q5YRd4X4cCkeDPDcJLgKW1jkCsA7yBqESXPDSkkrVUM06A9qMFUwk4mRI88fZ8ryQ==

I'm asking me how to verify it in php?

I tryed something like:

$rsa = new Crypt_RSA();
$rsa->loadKey('qH/J3/gvF/h5U02uPyC9Qzn/hHEV5DzB9nFfqk5zbQqHdInVe4sfL+npa+4fjLGrBU30Iuvcr+o9paEjzpH5dY48cq6JHqz1RyJ0CQIc2Jr5+sS4eL1ZIjxWlyN1pKMR+4aE2rlDAad56Ad1cytiaHuVvyK/gdtbKiuGroSQhJ1EVfZ60m3NIqnqmpi5Zdsnmzny4VH/d66BcGXxGaGaUaqFn0WTypuwIMZMMtzZEK7peKoaW4H4rfkfdrKcD8AaT+z9v5lLGkTl0NcZZ4LN9sSUzsHNfyAFK6cSXo/73z0tDAlGb5K+yWV6UHoYW1rcoIsxlNRZM6/6FYgMXbbfow=='); // public key
echo $rsa->verify('message', 'XbF4O6v6oadEQGtdpQ7d54Q2JB9/ZEXEUH3S1FMn4E/PSqk7HLXjG4tNfuiUBa5eS8kYV49gwC8Yr+mn6YUAHt+K9lHPSsmltWoiHNOaas4aqai9nlyeft4TYYhP+GYbQfw+3n2TcO39s6M0vw0m0a8AX9JfF02JwCUhP4bu4dzG6Bl5dj000TbUkric14Jyurp8OHmmMvKW62TvXPhNOW39+wS1Qkfn9Bxmzi8UEVSVe3wP45JWZNgmgeGnpubDhD05FJEDErfVtZ/DRKD81q5YRd4X4cCkeDPDcJLgKW1jkCsA7yBqESXPDSkkrVUM06A9qMFUwk4mRI88fZ8ryQ==') ? 'verified' : 'unverified';

I think the signature and/or public key are not formated correctly for php. Any idea?

Thank you in advance,

[EDIT] I'm not sure the signature is correct. If I use the js function cryptico.b64to16(signature), the signature will be somethink like :

5db1783babfaa1a744406b5da50edde78436241f7f6445c4507dd2d45327e04fcf4aa93b1cb5e31b8b4d7ee89405ae5e4bc918578f60c02f18afe9a7e985001edf8af651cf4ac9a5b56a221cd39a6ace1aa9a8bd9e5c9e7ede1361884ff8661b41fc3ede7d9370edfdb3a334bf0d26d1af005fd25f174d89c025213f86eee1dcc6e81979763d34d136d492b89cd78272baba7c3879a632f296eb64ef5cf84d396dfdfb04b54247e7f41c66ce2f141154957b7c0fe3925664d82681e1a7a6e6c3843d3914910312b7d5b59fc344a0fcd6ae5845de17e1c0a47833c37092e0296d63902b00ef206a1125cf0d2924ad550cd3a03da8c154c24e26448f3c7d9f2bc9

I am not sure about the format of the param key of $rsa->verify. I tryed to add the prefix ssh-rsa. But it do not works better.

So I tryed the to signature format and the to key. The message is each time "unverified"


Source: (StackOverflow)

Extract RSA private key from Cryptico.js

I believe this is a pretty basic question, but I'm starting the studies in JavaScript and in RSA, so I'm a little bit lost. I just downloaded the library Cryptico, which gives me an easy to use RSA key gen/encryption/decryption. The public part of the generated RSA Key, can be extracted easily just using the command:

publicKeyString(RsaKey)

Which is:

my.publicKeyString = function(rsakey) 
{
    pubkey = my.b16to64(rsakey.n.toString(16));
    return pubkey; 
}

The rsakey.n is defined while generating the key in the function:

function RSAGenerate(B, E)
{
    var rng = new SeededRandom();
    var qs = B >> 1;
    this.e = parseInt(E, 16);
    var ee = new BigInteger(E, 16);
    for (;;)
    {
        for (;;)
        {
            this.p = new BigInteger(B - qs, 1, rng);
            if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) break;
        }
        for (;;)
        {
            this.q = new BigInteger(qs, 1, rng);
            if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) break;
        }
        if (this.p.compareTo(this.q) <= 0)
        {
            var t = this.p;
            this.p = this.q;
            this.q = t;
        }
        var p1 = this.p.subtract(BigInteger.ONE);
        var q1 = this.q.subtract(BigInteger.ONE);
        var phi = p1.multiply(q1);
        if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0)
        {
            this.n = this.p.multiply(this.q);
            this.d = ee.modInverse(phi);
            this.dmp1 = this.d.mod(p1);
            this.dmq1 = this.d.mod(q1);
            this.coeff = this.q.modInverse(this.p);
            break;
        }
    }
}

But the private part of the key, I just can't understand how to extract, so I'll be able to save public/private key parts and available for later using.

Library Documentation: https://github.com/wwwtyro/cryptico


Source: (StackOverflow)

Decryption of encrypted text in PHP

I am trying to decode encrypted data in PHP, however the return value keeps coming back as null.

The data to be decrypted comes into the PHP file as a data argument.

$dataArg1 = $_REQUEST["data"];

// Retrieve $encryptedData from storage ...
//
// Load the private key and decrypt the encrypted data
$encryptedData = $dataArg1;
$privateKey = array ( array(123456,654321,123456), array(123456,1234),
                      array(1234567,4321)
                    );
    openssl_private_decrypt($encryptedData, $sensitiveData, $privateKey);

The function above comes from the second response of another posting here on Stack Overflow: How to encrypt data in javascript and decrypt in php?

I assume that the decrypted value is in the PHP variable, $sensitiveData.

When I echo that to the screen, I get nothing.

echo("sensitiveData=[$sensitiveData]<br />");

Thoughts?

UPDATE: The return value from openssl_private_decrypt() is FALSE, and the return value is NULL.

UPDATE 2: I created the public/private key from the following URL. http://shop-js.sourceforge.net/crypto2.htm

At the bottom, there is the line: And put the following in your private script (probably on your local hard disk -- not on the internet -- if your private key is found this whole thing is useless.)

<script>
function decrypt() {
 // key = [ [d], [p], [q] ];
 var key=[[123456789,123456789,123456789],[123456789,1234],[123456789,4321]];
 document.form.text.value=rsaDecode(key, document.form.text.value);
}
</script>
(actual values changed)

I copied translated the "var key=" line to PHP (per my other posting). Translation above using embedded arrays. I then past that key to the decrypt function.

My thought is that the PHP documentation calls the private key "mixed". I am wondering if maybe I need a different format for the private key.

Here is the output:

dataArg1=[jmOdss9ktFc\"WO5eltUZXt0rpqS1NluNKa]

bResult=[]

sensitiveData=[]

var_dump=[NULL ]

Source: (StackOverflow)

Encrypt message with Cryptico public key using PHP

Is it possible to generate an RSA public key from a passphrase using Cryptico, then use PHP to encrypt a message with that public key, and decrypt it with JavaScrpt using the original passphrase?

Cryptico seems to work great on its own, but I'm trying to use phpseclib to encrypt a message using the public key that Cryptico generated and i'm not getting an output. Even if I did, would I be able to base64 encode it and decrypt it with Cryptico?

Using the passphase "stackoverflow rocks" with Bits set to 1024 I get this public key:

XEjrqvt5K3pjM2m98ZFQOf9fObVNKPJQ9TYbo4sdNPaUO0NKdLtno8hXa292MiAmwip9JOiplmSQVEvpEnfebGNFFzqNgd4hAS6oXD6zHexVHsHpFTYxfVFQE93eHtbz0Mi7l64rnq6UOQKAB53CXVUev6RqyR6hs4oBiJRAOCs=

But when I use the following code with or without the PKCS1 line, I get no output.

$rsa = new Crypt_RSA();
$rsa->loadKey('XEjrqvt5K3pjM2m98ZFQOf9fObVNKPJQ9TYbo4sdNPaUO0NKdLtno8hXa292MiAmwip9JOiplmSQVEvpEnfebGNFFzqNgd4hAS6oXD6zHexVHsHpFTYxfVFQE93eHtbz0Mi7l64rnq6UOQKAB53CXVUev6RqyR6hs4oBiJRAOCs='); // public key

$plaintext = 'tester';
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->encrypt($plaintext);
echo $ciphertext;
?>

Does anyone know what i'm missing to make this work? - Or is this impossible and i'm wasting my time?

EDIT: ------------ Code i'm using re owlstead's comment ------------- Tried with and without the PKCS1 line

<?php
include('Crypt/RSA.php');

$rsa = new Crypt_RSA();
$rsa->loadKey('-----BEGIN PUBLIC KEY-----
XEjrqvt5K3pjM2m98ZFQOf9fObVNKPJQ9TYbo4sdNPaUO0NKdLtno8hXa292MiAmwip9JOiplmSQVEvpEnfebGNFFzqNgd4hAS6oXD6zHexVHsHpFTYxfVFQE93eHtbz0Mi7l64rnq6UOQKAB53CXVUev6RqyR6hs4oBiJRAOCs=
-----END PUBLIC KEY-----'); // public key

$plaintext = 'tester';
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->encrypt($plaintext);
echo $ciphertext;
?>

Source: (StackOverflow)