Showing posts with label openssl. Show all posts
Showing posts with label openssl. Show all posts

Wednesday, May 24, 2017

PHP Encrypt Data With OpenSSL Public Key And Decrypt With OpenSSL Private Key

Below is a PHP code snippet to encrypt data with a public key and then again decrypt the encrypted data with a private key.
 

If you have fetched the problem "error:0406D06E:rsa routines:RSA_padding_add_PKCS1_type_2:data too large for key size" then use the below code snippet to overcome this problem.
 

It's a good solution to handle big size data, but don't try too big size data with this method actually when you post file.
Raw data is fine.  




$data = "Large data to test. Large data to test. Large data to test. Large data to test.";
$data = $data . $data . $data . $data . $data . $data . $data . $data;
$data = $data . $data . $data . $data . $data . $data . $data . $data;
encryptAndDecrypt($data);

function encryptAndDecrypt($data)
{
    echo "Original data length=" . strlen($data) . "<BR>";

    $private_key = openssl_pkey_get_private(readServerFile("./XeroCerts/privatekey.pem"));
    $public_key = openssl_pkey_get_public(readServerFile("./XeroCerts/publickey.cer"));

    //Block size for encryption block cipher for 1024 bit key
    $encrypt_size = 110;

    //Block size for decryption block cipher for 1024 bit key
    $decrypt_size = 128;

    //For encryption we would use:
    $encrypted = '';
    $data = str_split($data, $encrypt_size);
    foreach ($data as $chunk) {
        openssl_public_encrypt($chunk, $partial, $public_key, OPENSSL_PKCS1_PADDING);
        $encrypted .= $partial;
    }
    openssl_free_key($public_key);
    $encrypted = base64_encode($encrypted);
    echo "Encrypted=" . $encrypted . "<BR>";

    //For decryption we would use:
    $decrypted = '';
    $data = str_split(base64_decode($encrypted), $decrypt_size);
    foreach ($data as $chunk) {
        openssl_private_decrypt($chunk, $partial, $private_key, OPENSSL_PKCS1_PADDING);
        $decrypted .= $partial;
    }
    openssl_free_key($private_key);
    echo "Decrypted=" . $decrypted;
    die();
}

Output of the above code snippet is below: 


If you don't want to save strings in clear text, there are new php functions (php >= 5.3.0) that can be of help; openssl_encrypt() and openssl_decrypt().

Original data length=5056
Encrypted=Vf2GHkx..............LgpFjM9gY/FkIYWaELHl3I=
Decrypted=Large data to test. ............ Large data to test. Large data to test. Large data to test.

Simple PHP encrypt and decrypt Using AES-256-CBC Algorithm | OpenSSL Encrypt | OpenSSL Decrypt

If you don't want to save strings in clear text, there are new php functions (php >= 5.3.0) that can be of help; openssl_encrypt() and openssl_decrypt(). 


<?php
define("SSL_SECRET_KEY", "SSL_SECRET_KEY");
define("SSL_SECRET_IV", "SSL_SECRET_IV");
define("SSL_ENCRYPTION_METHOD", "AES-256-CBC");
define("SSL_SECRET_IV_SIZE", openssl_cipher_iv_length(SSL_ENCRYPTION_METHOD));

function encryptData($string)
{
    $key = hash('sha256', SSL_SECRET_KEY);
    /* If you want random IV */
    //$iv = openssl_random_pseudo_bytes(SSL_SECRET_IV_SIZE);
    $iv = substr(hash('sha256', SSL_SECRET_IV), 0, SSL_SECRET_IV_SIZE);

    $output = openssl_encrypt($string, SSL_ENCRYPTION_METHOD, $key, 0, $iv);
    return base64_encode($output);
}

function decryptData($string)
{
    $key = hash('sha256', SSL_SECRET_KEY);
    $iv = substr(hash('sha256', SSL_SECRET_IV), 0, SSL_SECRET_IV_SIZE);

    return openssl_decrypt(base64_decode($string), SSL_ENCRYPTION_METHOD, $key, 0, $iv);
}

$REQUEST_URI = isset($_SERVER["REQUEST_URI"]) ? $_SERVER["REQUEST_URI"] : "";

if (strpos($REQUEST_URI, "enc.php") !== false) {
    $plain_txt = "Value to be encrypt & decrypt";
    echo "Original Text = $plain_txt<br/>";

    $encrypted_txt = encryptData($plain_txt);
    echo "Encrypted Text = $encrypted_txt<br/>";

    $decrypted_txt = decryptData($encrypted_txt);
    echo "Decrypted Text = $decrypted_txt<br/>";

    if ($plain_txt === $decrypted_txt) echo "SUCCESS";
    else echo "FAILED";

    echo "<br/>";
}


Original Text:
Value to be encrypt & decrypt

Encrypted Text = 
RjFhMElpR0VzMVlPeVdtREVraFJzYnhnNXZ4ck4vSmhRVUtXWXJoUzBVWT0=

Decrypted Text
Value to be encrypt & decrypt

SUCCESS 

Or (This will carry IV with encrypted text itself):

<?php
define("SSL_SECRET_KEY", "xorxorxorxorxor");
define("SSL_ENCRYPTION_METHOD", "AES-256-CBC");
define("SSL_SECRET_IV_SIZE", openssl_cipher_iv_length(SSL_ENCRYPTION_METHOD));

function encryptData($string)
{
    $key = hash('sha256', SSL_SECRET_KEY);
    $iv = openssl_random_pseudo_bytes(SSL_SECRET_IV_SIZE);

    $output = openssl_encrypt($string, SSL_ENCRYPTION_METHOD, $key, 0, $iv);
    return base64_encode($iv . ":" . $output);
}

function decryptData($string)
{
    $string = explode(":", base64_decode($string));
    $key = hash('sha256', SSL_SECRET_KEY);

    return openssl_decrypt($string[1], SSL_ENCRYPTION_METHOD, $key, 0, $string[0]);
}

$plain_txt = "Value to be encrypt & decrypt";
echo "Original Text = $plain_txt<br/>";

$encrypted_txt = encryptData($plain_txt);
echo "Encrypted Text = $encrypted_txt<br/>";

$decrypted_txt = decryptData($encrypted_txt);
echo "Decrypted Text = $decrypted_txt<br/>";

if ($plain_txt === $decrypted_txt) echo "SUCCESS";
else echo "FAILED";

echo "<br/>";

Original Text:

Value to be encrypt & decrypt

Encrypted Text:
NfDWpobv5RGaC29EpXvP7Dp2WkJjN2pETmdPendsZkdsMnBVQXBTK2pRekJTNkhlTndEdTRGd3h6eHpFPQ==

Decrypted Text:
Value to be encrypt & decrypt

SUCCESS

PHP - Sign Request Data With OpenSSL Private Key Pair

Below is a PHP code snippet to sign request data with OpenSSL private key. It's used to handshake with server to communicate with the server.

function signRequestParams($options)
{
    $private_key = openssl_pkey_get_private(readServerFile("./XeroCerts/privatekey.pem"));
    $sbs = escapeUrlEntity(normalizeParameters($options));
    openssl_sign($sbs, $signature, $private_key);
    openssl_free_key($private_key);
    return base64_encode($signature);
}

function readServerFile($file_path)
{
    $fp = fopen($file_path, "r");
    $file_contents = fread($fp, 8192);
    fclose($fp);
    return $file_contents;
}

function normalizeParameters($parameters)
{
    $elements = array();
    ksort($parameters);
    foreach ($parameters as $paramName => $paramValue) {
        /* If name contains "be_ignored" will be ignored */
        if (preg_match('/be_ignored/', $paramName))
            continue;
        if (is_array($paramValue)) {
            sort($paramValue);
            foreach ($paramValue as $element)
                array_push($elements, escapeUrlEntity($paramName) . '=' . escapeUrlEntity($element));
            continue;
        }
        array_push($elements, escapeUrlEntity($paramName) . '=' . escapeUrlEntity($paramValue));
    }
    return join('&', $elements);
}

function escapeUrlEntity($string)
{
    if ($string === 0)
        return 0;
    if (empty($string))
        return '';
    if (is_array($string))
        throw new Exception('Array passed to escapeUrlEntity');

    $string = rawurlencode($string);
    $string = str_replace('+', '%20', $string);
    $string = str_replace('!', '%21', $string);
    $string = str_replace('*', '%2A', $string);
    $string = str_replace('\'', '%27', $string);
    $string = str_replace('(', '%28', $string);
    $string = str_replace(')', '%29', $string);
    return $string;
}

$options = array(
    "card.PAN" => "4564710000000004",
    "card.CVN" => "847",
    "card.expiryMonth" => "12",
    "card.expiryYear" => "20"
);

$signature = signRequestParams($options);
echo "Signature=$signature";

Output will be as below:

Signature=UC/uRPTaNxMV02a9I/KlWL/BA8..............6Fx1hjEYHWXN0U=

Friday, May 5, 2017

Create public/private key pair using OAuth RSA-SHA1 method on Windows with OpenSSL

Download OpenSSL from http://slproweb.com/products/Win32OpenSSL.html
And install on your machine.

Or you can download light version from windows 32 bit from here.
Or you can download light version from windows 64 bit from here.

Open Command Prompt as Administrator and navigate to "C:\OpenSSL-Win32\bin". (Assumed that in that location your openssl installed)

Now execute the following three commands:

openssl genrsa -out privatekey.pem 1024

set OPENSSL_CONF=C:/OpenSSL-Win32/bin/openssl.cfg [It may  be .cfg or .cnf, check your bin directory]

openssl req -new -x509 -key privatekey.pem -out publickey.cer -days 1825

Below are two screen-shots:




Tuesday, July 23, 2013

Create Self-Signed Certificate Windows

At first install OpenSSL in your windows machine.

Several files related to your your SSL certificate will be created in this section, so choose a common base name to use. In my examples I use "blarg", which I've italicised to show it should be replaced by your choice. In practice, I recommend extracting the essence from your domain name; for example, if I was creating a certificate for https://www.neilstuff.com/ then I'd use "neilstuff".
Open up a command prompt and go to the directory where you unzipped OpenSSL and run the following command to create a new certificate request:

openssl req -config openssl.cnf -new -out blarg.csr -keyout blarg.pem


You'll be prompted to answer many questions, which ones depend on your openssl.cnf file; all except two of these can be left blank:
  • PEM pass phrase: Password associated with the private key (blarg.pem) you're generating. Since we'll be removing this for the benefit of Apache 2.0.X, I suggest using something like "none" or "password".
  • Common Name: The fully-qualified domain name associated with this certificate. In my example, I use www.blarg.com which means I damn well better use that certificate on https://www.blarg.com/. For personal security, testing, or intranets it's okay for this to not quite match -- just be prepared to deal with warnings from web browsers and such.
Now it's time to create a non-password protected key for Apache 2.0.X by executing the following:
openssl rsa -in blarg.pem -out blarg.key

The only thing you'll be asked is the password you had used. Your resulting KEY file is essential the same thing as the PEM, just not password protected.
Before we go on, delete the .rnd file. This contains entropy information which could be used by malicious people to try and crack your certificate later on (if they get a hold of it).
Finally, run the following command to create an X.509 certificate, e.g. the kind of certificate that SSL likes to munch:
openssl x509 -in blarg.csr -out blarg.cert -req -signkey blarg.key -days 365

 
Congratulations, you've created a self-signed certificate! Keep the KEY and CERT files some place safe, we'll be using them soon.

Installing OpenSSL on Windows


OpenSSL is officially distributed in C source code format. This is not a problem for Unix systems where C compiler is always available. But if you have a Windows system, you will have a hard time to install OpenSSL in C source code format. What you should do is to find a pre-compiled binary version for Windows. Here is my sugge I installed OpenSSL on my Windows system: 

1. Go to http://gnuwin32.sourceforge.net/packages/openssl.htm, and download the "Zip" version. 

2. Unzip the file somewhere on your computer. 

3. Copy all the libeay32.dll and ssleay32.dll to your Windows\System32 or xampp/php (if you are using xampp server) directory. If you've dealt with SSL at all before, especially as a developer, you might already have copies of these there. Keep whatever is newest.

4. Open command line window, and try the following command: 
Code:
>\local\gnuwin32\bin\openssl -help
openssl:Error: '-help' is an invalid command.

Standard commands
asn1parse      ca             ciphers        crl            crl2pkcs7
dgst           dh             dhparam        dsa            dsaparam
enc            engine         errstr         gendh          gendsa
genrsa         nseq           ocsp           passwd         pkcs12
pkcs7          pkcs8          rand           req            rsa
rsautl         s_client       s_server       s_time         sess_id
smime          speed          spkac          verify         version
x509
......
5. You'll also need an openssl.cnf which is an OpenSSL configuration file that, for some reason, doesn't come with Hunter's distribution. Download this one or this one or this one or this one and save it to the folder where you unzipped OpenSSL.

If you see the list of commands printed by OpenSSL, you know that your installation is done correctly.

------------ 
For other tutorials on OpenSSL, see http://www.herongyang.com/crypto/

__________________
Good tutorials for beginners on PHP, JSP, ASP, SQL, ... 
--> http://www.herongyang.com/

Sunday, April 7, 2013

Enable OpenSSL Support for PHP on Windows

Enable OpenSSL Support for PHP on Windows 

As a prerequisite, two libraries must be existing in your Windows system: libeay32.dll and ssleay32.dll. Two ways to achieve this:
  • Install OpenSSL for Windows
  • Or, copy these two files to C:\WINDOWS\system32 folder. They’re shipped with PHP package, you can find them in PHP root folder.
OK, it’s time to open php.ini by using any text editor, and remove the semicolon before the following line:
extension=php_openssl.dll
Done!
http://huang.yunsong.net/2009/windows-php-openssl.html