Encrypt Large Messages with Asymmetric Keys and phpseclib

View: 319    Dowload: 0   Comment: 0   Post by: hanhga  
Author: none   Category: Php&mySql   Fields: Other

9 point/3 review File has been tested

Most of us understand the need to encrypt sensitive data before transmitting it. Encryption is the process of translating plaintext (i.e. normal data) into ciphertext (i.e. secret data).

Introduction

Most of us understand the need to encrypt sensitive data before transmitting it. Encryption is the process of translating plaintext (i.e. normal data) into ciphertext (i.e. secret data). During encryption, plaintext information is translated to ciphertext using a key and an algorithm. To read the data, the ciphertext must be decrypted (i.e. translated back to plaintext) using a key and an algorithm.

An encryption algorithm is a series of mathematical operations applied to the numerical value(s) of the key and the numerical values of the characters in a string of plaintext. The results are the ciphertext. The larger the key, the more secure the ciphertext.

A core problem to be solved with any encryption algorithm is key distribution. How do you transmit keys to those who need them in order to establish secure communication?

The solution to the problem depends on the nature of the keys and algorithms.

Encryption Algorithms and Keys

There are two basic types of encryption algorithms: 
1. Symmetric Algorithms that use the same key for both encryption and decryption. 
2. Asymmetric Algorithms that use different keys for encryption and decryption.

If a symmetric algorithm is chosen, both the sender and the receiver must have the same key. If the sender and receiver are in different locations, the transmission of the key itself becomes a point of vulnerability.

If an asymmetric algorithm is chosen, there are two keys: a public key and a private key. Data encrypted with a public key can only be decrypted with the corresponding private key. The receiver first transmits their public key to the sender. The sender uses that public key to encrypt the message and then transmits the message to the receiver. The receiver decrypts the message with their private key.

With an asymmetric algorithm the receiver can transmit the public key to whomever they wish without fear of compromise because only the holder of the private key can decrypt the message.

Asymmetric algorithms solve the key distribution problem.

Selection of Encryption Algorithms

Strong cryptographic algorithms are based on advanced mathematics and number theory. Generally, a cryptographic algorithm is “strong” if, for a given key size, it would take an unfeasibly long time for someone without the key to decrypt the message.1

Because of the complexity of cryptographic algorithms, selecting one over another can be confusing to those without a strong background in mathematics. So, many commercial and government entities rely on the National Institute of Standards and Technology (NIST) – a non-regulatory US agency – for recommendations on strong cryptography.

NIST specifies three asymmetric algorithms: RSA, DSA and ECDSA. ECDSA is a relative new comer, so the two common asymmetric algorithms are RSA and DSA. RSA is often a preferred commercial algorithm because the standard easily allows for larger key size. 2.

In 2001, NIST selected the Rijndael algorithm as its preferred symmetric algorithm to replace its aging DES (Data Encryption Standard).3

The Problem with RSA Keys

Although asymmetric algorithms solve the key distribution problem, there is another problem. The nature of the RSA algorithm is such that it is only able to encrypt a limited amount of plaintext. For example, if your key size is 2048 bits, then you are limited to 256 bytes (at most) of plaintext data that can be encrypted.4

Here’s a summary our problem: 
1. Asymmetric Keys are easy to exchange securely, but have a limited message size. 
2. Symmetric Keys have an unlimited message size, but are difficult to exchange securely.

The Solution

The solution to the problem is to encrypt the message with a symmetric key, then asymmetrically encrypt the key and attach it to the message.

When the message arrives at the receiver, they will have both the symmetric key and the message. The receiver extracts the encrypted symmetric key, asymmetrically decrypts it, and then uses it to decrypt the rest of the message.

The following section explains both encryption and decryption processes step by step.

Encryption

  1. The receiver generates a key pair and transmits their public key to the sender.
  2. The sender generates a random symmetric key and uses it to encrypt the large message.
  3. The sender encrypts the message with the symmetric key.
  4. The sender encrypts the symmetric key with the receiver’s public key.
  5. The sender concatenates the encrypted symmetric key and the encrypted message.
  6. The sender transmits the encrypted message to the receiver.

Decryption

After the receiver gets the message, they will reverse the process: 
1. The receiver extracts the encrypted symmetric key from the message. 
2. The receiver decrypts the symmetric key using their private key. 
3. The receiver decrypts the message with the symmetric key.

Programming the Solution in PHP

To demonstrate this technique we will use the PHP Secure Communications Library. This library (phpseclib) contains free and open source pure-PHP implementations of arbitrary-precision integers, RSA, DES, 3DES, RC4, Rijndael, AES, SSH-1, SSH-2, and SFTP.

The library is designed in such a way that it takes advantage of faster encryption functions (such as open_ssl and mcrypt), if they are available, for performance purposes. However, sometimes, these libraries and functions are not available to PHP programmers (in a shared hosting environment for example). So, phpseclib is designed to work reliably, albeit more slowly, if only PHP is available.

You can install it via Composer.

Documentation for phpseclib can be found at http://phpseclib.sourceforge.net/documentation/index.html

Sample Code

Let’s write our demo code step by step.

Generate Public and Private Keys

The RSA class contains a key generation method. In the example below, you see how we generate and save the key pair. In an actual production environment, the private key would be stored in a safe location until it was time to decrypt the message. The public key would be transmitted to the sender of the message.

$rsa = new Crypt_RSA();
 $keys = $rsa->createKey(2048);
 
 file_put_contents('key.pri',$keys['privatekey']);
 file_put_contents('key.pub',$keys['publickey']);

Encrypt Function

The encrypt_message function takes three parameters: 
1. $plaintext – The plaintext message to be encrypted. 
2. $asym_key – This is the public key provided to the sender by the receiver 
3. $key_length – This is an arbitrary length key, but should be less than 240. The larger the number, the less likely a brute force attack is to succeed. This is an optional parameter.

function encrypt_message($plaintext,$asym_key,$key_length=150)
 {
           
      $rsa = new Crypt_RSA();
      $rij = new Crypt_Rijndael();
  
     
     // Generate Random Symmetric Key
     $sym_key = crypt_random_string($key_length); 
     
     // Encrypt Message with new Symmetric Key                  
     $rij->setKey($sym_key);
     $ciphertext = $rij->encrypt($plaintext);
     $ciphertext = base64_encode($ciphertext); 
     
     // Encrypted the Symmetric Key with the Asymmetric Key            
     $rsa->loadKey($asym_key);
     $sym_key = $rsa->encrypt($sym_key);
     
     // Base 64 encode the symmetric key for transport
     $sym_key = base64_encode($sym_key);
     $len = strlen($sym_key); // Get the length
     
     $len = dechex($len); // The first 3 bytes of the message are the key length
     $len = str_pad($len,3,'0',STR_PAD_LEFT); // Zero pad to be sure.
     
     // Concatenate the length, the encrypted symmetric key, and the message
     $message = $len.$sym_key.$ciphertext;

      return $message;
 }

Decrypt Function

The decrypt function takes two parameters: 
1. $message – The message to be decrypted 
2. $asym_key – The private key of the receiver.

function decrypt_message($message,$asym_key)
 {
      
     $rsa = new Crypt_RSA();
     $rij = new Crypt_Rijndael();
 
     // Extract the Symmetric Key  
     $len = substr($message,0,3); 
     $len = hexdec($len);                        
     $sym_key = substr($message,0,$len);
     
     //Extract the encrypted message
     $message = substr($message,3);
     $ciphertext = substr($message,$len);
     $ciphertext = base64_decode($ciphertext);
     
     // Decrypt the encrypted symmetric key 
     $rsa->loadKey($asym_key);
     $sym_key = base64_decode($sym_key);
     $sym_key = $rsa->decrypt($sym_key);
    
     // Decrypt the message
     $rij->setKey($sym_key);                       
     $plaintext = $rij->decrypt($ciphertext);
                                                     
 return $plaintext;
 }

 

Encrypt Large Messages with Asymmetric Keys and phpseclib

Encrypt Large Messages with Asymmetric Keys and phpseclib Posted on 16-03-2016  Most of us understand the need to encrypt sensitive data before transmitting it. Encryption is the process of translating plaintext (i.e. normal data) into ciphertext (i.e. secret data). 3/10 319

Comment:

To comment you must be logged in members.

Files with category

  • How to Picking the Brains of Your Customers with Microsoft’s Text Analytics

    View: 3932    Download: 0   Comment: 0   Author: none  

    How to Picking the Brains of Your Customers with Microsoft’s Text Analytics

    Category: Php&mySql
    Fields: Other

    2.5/2 review
    With the explosion of machine learning services in recent years, it has become easier than ever for developers to create “smart apps”. In this article, I’ll introduce you to Microsoft’s offering for providing machine-learning capabilities to apps.

  • How to MySqli Tutorial PHP MySqli Extension

    View: 358    Download: 0   Comment: 0   Author: none  

    How to MySqli Tutorial PHP MySqli Extension

    Category: Php&mySql
    Fields: Other

    0/0 review
    PHP provides three api to connect mysql Database.

  • Make Laravel Artisan Commands

    View: 332    Download: 0   Comment: 0   Author: none  

    Make Laravel Artisan Commands

    Category: Php&mySql
    Fields: Other

    0/0 review
    Artisan is the command line tool used in Laravel framework. It offers a bunch of useful command that can help you develop application quickly. Apart from Artisan available commands, you can create your own custom commands to improve your workflow.

  • Check if a Number is a Power of 2

    View: 313    Download: 0   Comment: 0   Author: none  

    Check if a Number is a Power of 2

    Category: Php&mySql
    Fields: Other

    1.5/3 review
    How to check if a number is a power of 2. To understand this question, let’s take some example.

  • Concatenate columns in MySql

    View: 375    Download: 0   Comment: 0   Author: none  

    Concatenate columns in MySql

    Category: Php&mySql
    Fields: Other

    0/2 review
    Artisan is the command line tool used in Laravel framework. It offers a bunch of useful command that can help you develop application quickly. Apart from Artisan available commands, you can create your own custom commands to improve your workflow

  • How to Query NULL Value in MySql

    View: 311    Download: 0   Comment: 0   Author: none  

    How to Query NULL Value in MySql

    Category: Php&mySql
    Fields: Other

    5/1 review
    Misunderstanding NULL is common mistake beginners do while writing MySql query. While quering in MySql they compare column name with NULL. In MySql NULL is nothing or in simple word it isUnknown Value so if you use comparison operator for NULL values...

  • How to Abstract Class in PHP

    View: 349    Download: 0   Comment: 0   Author: none  

    How to Abstract Class in PHP

    Category: Php&mySql
    Fields: Other

    0/0 review
    What is an abstract class in PHP and when to use an abstract class in your application. In this tutorial, we’ll learn about abstract class and their implementation.

  • Use Enums in Rails for Mapped Values

    View: 310    Download: 0   Comment: 0   Author: none  

    Use Enums in Rails for Mapped Values

    Category: Php&mySql
    Fields: Other

    2.5/2 review
    When I worked in a call center, we used to mark cases with different statuses. This allowed upper management to get a handle on where cases stood, what the bottlenecks were and flow of calls. Thankfully it has been a long time since I worked in a...

 

File suggestion for you

File top downloads

logo codetitle
Codetitle.com - library source code to share, download the file to the community
Copyright © 2015. All rights reserved. codetitle.com Develope by Vinagon .Ltd