Showing posts with label decrypt. Show all posts
Showing posts with label decrypt. 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

Saturday, June 28, 2014

Encrypt & Decrypt String Using AES Algorithm & jQuery


<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="crypto-js/core-min.js"></script>
<script src="crypto-js/enc-utf16-min.js"></script>
<script src="crypto-js/enc-base64-min.js"></script>
<script src="crypto-js/aes.js"></script>
<script>
 $(function() {
  $('#test').on('submit', function() {
   var plaintext = $('#text').val();
   var secret = $('#secret').val();
   var encrypted = '' + CryptoJS.AES.encrypt(plaintext, secret);
   $("#output").prepend("<br/>Encrypted: " + encrypted);
   var decrypted = CryptoJS.AES.decrypt(encrypted, secret);
   $("#output").prepend("<br/><br/> Original From Encrypted: " + decrypted.toString(CryptoJS.enc.Utf8));

   return false;
  });  
 });   
</script>
</head> 
<body lang="en">  
    <form id="test">
        <p>
            <label>Secret</label><br>
            <input id="secret" value="Secret Passphrase">
        </p>
        <p>
            <label>Text</label><br>
            <textarea id="text">This is the secret message</textarea>
        </p>
        <input type="submit" id="submit">
    </form>
    <div id="output"></div>  
</body>
</html>


Thursday, November 22, 2012

Encrypt and decrypt string using AES 128 and PKCS7 algorithm using Php

Encrypt and decrypt string using AES algorithm executed by PHP script is given below:


<?php
function encrypt($key, $to_encrypt)
{
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);
    $pad = $iv_size - (strlen($to_encrypt) % $iv_size);
    $to_encrypt = str_pad($to_encrypt, ($iv_size * (floor(strlen($to_encrypt) / $iv_size) + 1)), chr($pad));
    return base64_encode($iv . mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $to_encrypt, MCRYPT_MODE_CBC, $iv));
}

function decrypt($key, $to_decrypt)
{
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = substr($to_decrypt, 0, $iv_size);
    $to_decrypt = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, substr($to_decrypt, $iv_size), MCRYPT_MODE_CBC, $iv);
    $pad = ord($to_decrypt[strlen($to_decrypt) - 1]);
    return substr($to_decrypt, 0, -$pad);
}

$key = "1111111111111111";

$str = "Value to be encrypt";
$enc = encrypt($key, $str);
$dec = decrypt($key, base64_decode($enc));

echo "Original=" . $str;
echo "<BR>Encrypted=" . $enc;
echo "<BR>Decrypted=" . $dec;

Below is output:

Original=Value to be encrypt
Encrypted=fyqhmBCGLVXcT5tvq38G/MAlpgP2FYq29wgC7KIMT8jt6Z45cq63oJeY8kGgv9QP
Decrypted=Value to be encrypt
 
 

Encrypt and decrypt string using AES algorithm using Java

Encrypt and decrypt string or bytes using AES algorithm performed by Java code. below is the code snippet. 

package com.pkm;

import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class EncryptUtils {
    private static String algorithm = "AES";
    private static byte[] keyValue = "1111111111111111".getBytes();
    private static SecureRandom iv = new SecureRandom("192837465UTYELBN".getBytes());
    
    public static void main(String[] args) throws Exception {
        String valueToEncrypt = "Some value";
        String encryptedValue = encrypt(valueToEncrypt);
        System.out.println("Encrypted=" + encryptedValue);
        
        String afterDecrypt = decrypt(encryptedValue);
        System.out.println("Decrypted=" + afterDecrypt);
    }

    static String encrypt(String value) throws Exception {
        Key key = generateKey();
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);
        byte [] encByte = cipher.doFinal(value.getBytes());
        String encString = new BASE64Encoder().encode(encByte);
        return encString;
    }

    static String decrypt(String value) throws Exception {
        Key key = generateKey();
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte [] decByte64 = new BASE64Decoder().decodeBuffer(value);
        byte [] decByte = cipher.doFinal(decByte64);
        String decString = new String(decByte);
        return decString;
    }

    static private Key generateKey() throws Exception {
        return new SecretKeySpec(keyValue, algorithm);
    }
}


Below is output:

Original=Some value
Encrypted=i4he5mR49eRkWmQRVh12yg==
Decrypted=Some value