Friday 29 August 2014

Inserting Multidimensional php array into mysql

<?php_
$ppl = Array
 (
     [0] => Array
         (
             [first] => Keith
             [last] => Armstrong
         )

     [1] => Array
         (
             [first] => Farhan
             [last] => Daya
         )

     [2] => Array
         (
             [first] => Sean
             [last] => Do
         )
 )

foreach( $ppl as &$person ){
  $sql = "INSERT INTO ppl (first, last) VALUES ($person.first, $person.last)";
}
?>

Allowing User To Upload Files

PHP makes uploading files easy. You can upload any type of file to your Web server. But with ease comes danger and you should be careful when allowing file uploads.
In spite of security issues that should be addressed before enabling file uploads, the actual mechanisms to allow this are straight forward. In this tutorial we will consider how to upload files to some directory on your Web server. We will also discuss security issues concerned with the file uploading.
The HTML Form
Before you can use PHP to manage your uploads, you need first construct an HTML form as an interface for a user to upload his file. Have a look at the example below and save this HTML code as index.php.
<html>
<body>
  <form enctype="multipart/form-data" action="upload.php" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
    Choose a file to upload: <input name="uploaded_file" type="file" />
    <input type="submit" value="Upload" />
  </form>
</body>
</html>
There are some rules you need to follow when constructing your HTML form. First, make sure that the form uses the POST method. Second, the form needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting information back to server. Without these requirements, your file upload will not work.
Another thing to notice is the hidden form field named MAX_FILE_SIZE. Some web browsers actually pick up on this field and will not allow the user to upload a file bigger than this number (in bytes). You should set this value to coincide with the maximum upload size that is set in your php.ini file. It is set with the upload_max_filesize directive and the default is 2MB. But it still cannot ensure that your script won't be handed a file of a larger size. The danger is that an attacker will try to send you several large files in one request and fill up the file system in which PHP stores the decoded files. Set the post_max_size directive in your php.ini file to the maximum size that you want (must be greater than upload_max_filesize). The default is 10MB. This directive controls the maximum size of all the POST data allowed in a single request. Also make sure that file_uploads inside your php.ini file is set to On.
At least, have a look at the input tag attribute: type="file". It is used to designate the input element as a file select control. This provides a place for the URI of a file to be typed and a "Browse" button which can be used as an alternative to typing the URI.
After the user enters the URI of a file and clicks the Submit button the copy of the file will be sent to the server and the user will be redirected to upload.php. This PHP file will process the form data.
Back to top
Processing the Form Data (PHP Code)
When the file was uploaded, PHP created a temporary copy of the file, and built the superglobal $_FILES array containing information about the file. For each file, there are five pieces of data. We had named our upload field 'uploaded_file', so the following data would exist:
  • $_FILES["uploaded_file"]["name"] the original name of the file uploaded from the user's machine
  • $_FILES["uploaded_file"]["type"] the MIME type of the uploaded file (if the browser provided the type)
  • $_FILES["uploaded_file"]["size"] the size of the uploaded file in bytes
  • $_FILES["uploaded_file"]["tmp_name"] the location in which the file is temporarily stored on the server
  • $_FILES["uploaded_file"]["error"] an error code resulting from the file upload
The example below accepts an uploaded file and saves it in the upload directory. It allows to upload only JPEG images under 350Kb. The code, itself, is rather clear, but we will give a little explanation. Have a look at the example and save this PHP code as upload.php.
<?php
//Сheck that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
  //Check if the file is JPEG image and it's size is less than 350Kb
  $filename = basename($_FILES['uploaded_file']['name']);
  $ext = substr($filename, strrpos($filename, '.') + 1);
  if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") &&
    ($_FILES["uploaded_file"]["size"] < 350000)) {
    //Determine the path to which we want to save this file
      $newname = dirname(__FILE__).'/upload/'.$filename;
      //Check if the file with the same name is already exists on the server
      if (!file_exists($newname)) {
        //Attempt to move the uploaded file to it's new place
        if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) {
           echo "It's done! The file has been saved as: ".$newname;
        } else {
           echo "Error: A problem occurred during file upload!";
        }
      } else {
         echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists";
      }
  } else {
     echo "Error: Only .jpg images under 350Kb are accepted for upload";
  }
} else {
 echo "Error: No file uploaded";
}
?>
Before you do anything with the uploaded file you need to determine whether a file was really uploaded. After that we check if the uploaded file is JPEG image and its size is less than 350Kb. Next we determine the path to which we want to save this file and check whether there is already a file with such name on the server. When all checks are passed we copy the file to a permanent location using the move_upload_file() function. This function also confirms that the file you're about to process is a legitimate file resulting from a user upload. If the file is uploaded successfully then the corresponding message will appear. 
Note: Be sure that PHP has permission to read and write to the directory in which temporary files are saved and the location in which you're trying to copy the file.
This example is rather simple and its propose is to demonstrate you how to upload files using PHP. For example, you can add new conditions and allow to upload GIF and PNG images, or any other kind of files that you want. If you are unfamiliar with PHP this tutorial may be a good place to start.

Thursday 28 August 2014

Types of Encryption - Conventional Methods

Types of Encryption - Conventional Methods

  • Encryption - Decryption:

    To carry sensitive information, such as military or financial data, a system must be able to assure privacy. Microwave, satellite, and other wireless media, however, cannot be protected from the unauthorized reception (or interception) of transmissions. Even cable systems cannot always prevent unauthorized access. Cables pass through out-of-the-way areas (such as basements) that provide opportunities for malicious access to the cable and illegal reception of information.
    It is unlikely that any system can completely prevent unauthorized access to trans¬mission media. A more practical way to protect information is to alter it so that only an authorized receiver can understand it. Data tampering is not a new issue, nor is it unique to the computer era. In fact, efforts to make information unreadable by unautho­rized receivers date from Julius Caesar (100-44 B.C.). The method used today is called the encryption and decryption of information. Encryption means that the sender trans­forms the original information to another form and sends the resulting unintelligible message out over the network. Decryption reverses the encryption process in order to transform the message back to its original form.

    Figure 1 shows the basic encryption/decryption process. The sender uses an encryption algorithm and a key to transform the plaintext (as the original message is called) into a cipher text (as the encrypted message is called). The receiver uses a decryption algorithm and a key to transform the cipher text back to the original plaintext.


    Sender(Plain Text) --> Encryption Algorithm (ke) --> Cipher Text --> Decryption Algorithm (Kd)--> Receiver(Plain Text)
    Figure 1


    There are several data encryption standards and data encryption algorithms. However, Encryption and decryption methods fall into 2 categories:
    1. Conventional Method, and
    2. Pub­lic key Method.
    Conventional Method
    In conventional encryption methods, the encryption key (Ke) and the decryption key (Kd) are the same and remain secret. We can divide the conventional methods into 2 categories: Character-level encryption, and Bit-level encryption.
    Public Key Method
    In this method, every user has the same encryption algorithm and the key. The decryption algorithm and the key, however, are kept secret. Anyone can encrypt the information, but only an authorized receiver can decrypt it.
  • Character-Level Encryption


    In this method, encryption is done at the character level. There are two general methods for character-level encryption: substitution and transpositional.


    Substitutional


    The simplest form of character-level encryption is substitution ciphering. In monoalphabetic substitution, sometimes called the Caesar Cipher each character is replaced by another character in the set. The monoalphabetic encryption algorithm simply adds a number to the ASCII code of the character; the decryption algorithm simply subtracts the same number from the ASCII co. Ke and Kd are the same and define the added or subtracted value. To make it simple, we do not encode the space charac­ter. If the substituted character is beyond the last character (Z), we wrap it around.


    Monoalphabetic substitution is very simple, but the code can be broken easily by snoopers. The reason is that the method cannot hide the natural frequencies: characters in the language being used. For example, in English, the most fre­quently used characters are E, T, O, and A. A snooper can easily break the code by finding which character is used the most and replace that one with the letter E. It can then find the next most frequent and replace it with T, and so on.

    In polyalphabetic substitution, each occurrence of a character can have a different substitute. One polyalphabetic encryption technique is to find the position of the character in the text and use that value as the key. However, polyalphabetic substitution is not very secure either. The reason is that although "DEAR DEAR" is replaced by "EGDV JLIA", the order of characters in "EGDV" and "JLIA" is still the same; the code can easily be broken by a more experienced snooper.


    Transpositional


    An even more secure method is transpositional encryption, in which the original characters remain the same but the positions of these characters are interchanged to create the cipher text. The text is organized into a two-dimensional table, and the columns are interchanged according to a key. For example, we can organize the plaintext into an eleven-column table and then reorganize the columns according to a key that indicates the interchange rule. As you have guessed, transpositional encryption is not very secure either. The character frequen­cies are preserved and the snooper can find the plaintext through trial and error.
  • Bit-Level Encryption


    In Bit-level encryption techniques, data as text, graphics, audio, or video are divided into different blocks of bits and then each block is altered using either of the techniques: encoding/decoding, permutation, substitution, etc.

Encryption Algorithms

Encryption Algorithms

Encryption Algorithms

Encryption algorithm, or cipher, is a mathematical function used in the encryption and decryption process - series of steps that mathematically transforms plaintext or other readable information into unintelligible ciphertext. A cryptographic algorithm works in combination with a key (a number, word, or phrase) to encrypt and decrypt data. To encrypt, the algorithm mathematically combines the information to be protected with a supplied key. The result of this combination is the encrypted data. To decrypt, the algorithm performs a calculation combining the encrypted data with a supplied key. The result of this combination is the decrypted data. If either the key or the data is modified, the algorithm produces a different result. The goal of every encryption algorithm is to make it as difficult as possible to decrypt the generated ciphertext without using the key.
Each algorithm uses a string of bits known as a "key" to perform the calculations. The larger the key (the more bits), the greater the number of potential patterns can be created, thus making it harder to break the code and descramble the contents. Most encryption algorithms use the block cipher method, which codes fixed blocks of input that are typically from 64 to 128 bits in length. Some use the stream method, which works with the continuous stream of input.

Some cryptographic methods rely on the secrecy of the encryption algorithms; such algorithms are only of historical interest and are not adequate for real-world needs. Instead of the secrecy of the method itself, all modern algorithms base their security on the usage of a key; a message can be decrypted only if the key used for decryption matches the key used for encryption.

Types of encryption algorithms

There are two kinds of key-based encryption algorithms, symmetric encryption algorithms (secret key algorithms) and asymmetric encryption algorithms (or public key algorithms). The difference is that symmetric encryption algorithms use the same key for encryption and decryption (or the decryption key is easily derived from the encryption key), whereas asymmetric encryption algorithms use a different key for encryption and decryption, and the decryption key cannot be derived from the encryption key.

Symmetric encryption algorithms

Symmetric encryption algorithms can be divided into stream ciphers and block ciphers. Stream ciphers encrypt a single bit of plaintext at a time, whereas block ciphers take a number of bits (typically 64 bits in modern ciphers), and encrypt them as a single unit.

Some examples of popular symmetric encryption algorithms:
AES/Rijndael
Blowfish
CAST5
DES
IDEA
RC2
RC4
RC6
Serpent
Triple DES
Twofish

AES encryption algorithm

AES stands for Advanced Encryption Standard. AES is a symmetric key encryption technique which will replace the commonly used Data Encryption Standard (DES). It was the result of a worldwide call for submissions of encryption algorithms issued by the US Government's National Institute of Standards and Technology (NIST) in 1997 and completed in 2000.
In response to the growing feasibility of attacks against DES, NIST launched a call for proposals for an official successor that meets 21st century security needs. This successor is called the Advanced Encryption Standard (AES).
Five algorithms were selected into the second round, from which Rijndael was selected to be the final standard. NIST gave as its reasons for selecting Rijndael that it performs very well in hardware and software across a wide range of environments in all possible modes. It has excellent key setup time and has low memory requirements, in addition its operations are easy to defend against power and timing attacks. NIST stated that all five finalists had adequate security and that there was nothing wrong with the other four ciphers.
The winning algorithm, Rijndael, was developed by two Belgian cryptologists, Vincent Rijmen and Joan Daemen.
AES provides strong encryption and was selected by NIST as a Federal Information Processing Standard in November 2001 (FIPS-197).
Rijndael follows the tradition of square ciphers. AES algorithm uses three key sizes: a 128-, 192-, or 256-bit encryption key. Each encryption key size causes the algorithm to behave slightly differently, so the increasing key sizes not only offer a larger number of bits with which you can scramble the data, but also increase the complexity of the cipher algorithm.

Blowfish encryption algorithm

Blowfish is a symmetric encryption algorithm designed in 1993 by Bruce Schneier as an alternative to existing encryption algorithms.
Blowfish has a 64-bit block size and a variable key length - from 32 bits to 448 bits. It is a 16-round Feistel cipher and uses large key-dependent S-boxes. While doing key scheduling, it generates large pseudo-random lookup tables by doing several encryptions. The tables depend on the user supplied key in a very complex way. This approach has been proven to be highly resistant against many attacks such as differential and linear cryptanalysis. Unfortunately, this also means that it is not the algorithm of choice for environments where a large memory space is not available. Blowfish is similar in structure to CAST-128, which uses fixed S-boxes.

Since then Blowfish has been analyzed considerably, and is gaining acceptance as a strong encryption algorithm.
Blowfish was designed in 1993 by Bruce Schneier as a fast, free alternative to existing encryption algorithms. Since then it has been analyzed considerably, and it is slowly gaining acceptance as a strong encryption algorithm. Blowfish is unpatented and license-free, and is available free for all uses.

The only known attacks against Blowfish are based on its weak key classes.

CAST

CAST stands for Carlisle Adams and Stafford Tavares, the inventors of CAST. CAST is a popular 64-bit block cipher which belongs to the class of encryption algorithms known as Feistel ciphers.
CAST-128 is a DES-like Substitution-Permutation Network (SPN) cryptosystem. It has the Feistel structure and utilizes eight fixed S-boxes. CAST-128 supports variable key lenghts between 40 and 128 bits.
CAST-128 is resistant to both linear and differential cryptanalysis. Currently, there is no known way of breaking CAST short of brute force. CAST is now the default cipher in PGP.

Data Encryption Standard (DES)

Digital Encryption Standard (DES) is a symmetric block cipher with 64-bit block size that uses using a 56-bit key.

In 1977 the Data Encryption Standard (DES), a symmetric algorithm, was adopted in the United States as a federal standard.

DES encrypts and decrypts data in 64-bit blocks, using a 56-bit key. It takes a 64-bit block of plaintext as input and outputs a 64-bit block of ciphertext. Since it always operates on blocks of equal size and it uses both permutations and substitutions in the algorithm. DES has 16 rounds, meaning the main algorithm is repeated 16 times to produce the ciphertext. It has been found that the number of rounds is exponentially proportional to the amount of time required to find a key using a brute-force attack. So as the number of rounds increases, the security of the algorithm increases exponentially.

For many years, DES-enciphered data were safe because few organizations possessed the computing power to crack it. But in July 1998 a team of cryptographers cracked a DES-enciphered message in 3 days, and in 1999 a network of 10,000 desktop PCs cracked a DES-enciphered message in less than a day. DES was clearly no longer invulnerable and since then Triple DES (3DES) has emerged as a stronger method.

Triple DES encrypts data three times and uses a different key for at least one of the three passes giving it a cumulative key size of 112-168 bits. That should produce an expected strength of something like 112 bits, which is more than enough to defeat brute force attacks. Triple DES is much stronger than (single) DES, however, it is rather slow compared to some new block ciphers. However, cryptographers have determined that triple DES is unsatisfactory as a long-term solution, and in 1997, the National Institute of Standards and Technology (NIST) solicited proposals for a cipher to replace DES entirely, the Advanced Encryption Standard (AES).

IDEA encryption algorithm

IDEA stands for International Data Encryption Algorithm. IDEA is a symmetric encryption algorithm that was developed by Dr. X. Lai and Prof. J. Massey to replace the DES standard. Unlike DES though it uses a 128 bit key. This key length makes it impossible to break by simply trying every key. It has been one of the best publicly known algorithms for some time. It has been around now for several years, and no practical attacks on it have been published despite of numerous attempts to analyze it.
IDEA is resistant to both linear and differential analysis.

RC2

RC2 is a variable-key-length cipher. It was invented by Ron Rivest for RSA Data Security, Inc. Its details have not been published.

RC4

RC4 was developed by Ron Rivest in 1987. It is a variable-key-size stream cipher. It is a cipher with a key size of up to 2048 bits (256 bytes). The algorithm is very fast. Its security is unknown, but breaking it does not seem trivial either. Because of its speed, it may have uses in certain applications. It accepts keys of arbitrary length. RC4 is essentially a pseudo random number generator, and the output of the generator is exclusive-ored with the data stream. For this reason, it is very important that the same RC4 key never be used to encrypt two different data streams.

RC6

RC6 is a symmetric key block cipher derived from RC5. It was designed by Ron Rivest, Matt Robshaw, Ray Sidney, and Yiqun Lisa Yin to meet the requirements of the Advanced Encryption Standard (AES) competition. RC6 encryption algorithm was selected among the other finalists to become the new federal Advanced Encryption Standard (AES).

SEED

SEED is a block cipher developed by the Korea Information Security Agency since 1998. Both the block and key size of SEED are 128 bits and it has a Feistel Network structure which is iterated 16 times. It has been designed to resist differential and linear cryptanalysis as well as related key attacks. SEED uses two 8x8 S-boxes and mixes the XOR operation with modular addition. SEED has been adopted as an ISO/IEC standard (ISO/IEC 18033-3), an IETF RFC, RFC 4269 as well as an industrial association standard of Korea (TTAS.KO-12.0004/0025).

Serpent

Serpent is a very fast and reasonably secure block cipher developed by Ross Anderson, Eli Biham and Lars Knudsen. Serpent can work with different combinations of key lengths. Serpent was also selected among other five finalists to become the new federal Advanced Encryption Standard (AES).

TEA

Tiny Encryption Algorithm is a very fast and moderately secure cipher produced by David Wheeler and Roger Needham of Cambridge Computer Laboratory. There is a known weakness in the key schedule, so it is not recommended if utmost security is required. TEA is provided in 16 and 32 round versions. The more rounds (iterations), the more secure, but slower.

Triple DES

Triple DES is a variation of Data Encryption Standard (DES). It uses a 64-bit key consisting of 56 effective key bits and 8 parity bits. The size of the block for Triple-DES is 8 bytes. Triple-DES encrypts the data in 8-byte chunks. The idea behind Triple DES is to improve the security of DES by applying DES encryption three times using three different keys. Triple DES algorithm is very secure (major banks use it to protect valuable transactions), but it is also very slow.

Twofish

Twofish is a symmetric block cipher. Twofish has a block size of 128 bits and accepts keys of any length up to 256 bits.Twofish has key dependent S-boxes like Blowfish.
Twofish encryption algorithm was designed by Bruce Schneier, John Kelsey, Chris Hall, Niels Ferguson, David Wagner and Doug Whiting. The National Institute of Standards and Technology (NIST) investigated Twofish as one of the candidates for the replacement of the DES encryption algorithm.

Asymmetric encryption algorithms

Asymmetric encryption algorithms (public key algorithms) use different keys for encryption and decryption, and the decryption key cannot (practically) be derived from the encryption key. Public key methods are important because they can be used for transmitting encryption keys or other data securely even when the parties have no opportunity to agree on a secret key in private.

Types of Asymmetric encryption algorithms (public key algorithms):
RSA encryption algorithm
Diffie-Hellman
Digital Signature Algorithm
ElGamal
ECDSA
XTR

RSA encryption algorithm

Rivest-Shamir-Adleman is the most commonly used public key encryption algorithm. It can be used both for encryption and for digital signatures. The security of RSA is generally considered equivalent to factoring, although this has not been proved.
RSA computation occurs with integers modulo n = p * q, for two large secret primes p, q. To encrypt a message m, it is exponentiated with a small public exponent e. For decryption, the recipient of the ciphertext c = me (mod n) computes the multiplicative reverse d = e-1 (mod (p-1)*(q-1)) (we require that e is selected suitably for it to exist) and obtains cd = m e * d = m (mod n). The private key consists of n, p, q, e, d (where p and q can be omitted); the public key contains only n and e. The problem for the attacker is that computing the reverse d of e is assumed to be no easier than factorizing n.
The key size should be greater than 1024 bits for a reasonable level of security. Keys of size, say, 2048 bits should allow security for decades.
There are actually multiple incarnations of this algorithm; RC5 is one of the most common in use, and RC6 was a finalist algorithm for AES.

Diffie-Hellman

Diffie-Hellman is the first public key encryption algorithm, invented in 1976, using discrete logarithms in a finite field. Allows two users to exchange a secret key over an insecure medium without any prior secrets.

Diffie-Hellman (DH) is a widely used key exchange algorithm. In many cryptographical protocols, two parties wish to begin communicating. However, let's assume they do not initially possess any common secret and thus cannot use secret key cryptosystems. The key exchange by Diffie-Hellman protocol remedies this situation by allowing the construction of a common secret key over an insecure communication channel. It is based on a problem related to discrete logarithms, namely the Diffie-Hellman problem. This problem is considered hard, and it is in some instances as hard as the discrete logarithm problem.
The Diffie-Hellman protocol is generally considered to be secure when an appropriate mathematical group is used. In particular, the generator element used in the exponentiations should have a large period (i.e. order). Usually, Diffie-Hellman is not implemented on hardware.

Digital Signature Algorithm

Digital Signature Algorithm (DSA) is a United States Federal Government standard or FIPS for digital signatures. It was proposed by the National Institute of Standards and Technology (NIST) in August 1991 for use in their Digital Signature Algorithm (DSA), specified in FIPS 186 [1], adopted in 1993. A minor revision was issued in 1996 as FIPS 186-1 [2], and the standard was expanded further in 2000 as FIPS 186-2 [3]. Digital Signature Algorithm (DSA) is similar to the one used by ElGamal signature algorithm. It is fairly efficient though not as efficient as RSA for signature verification. The standard defines DSS to use the SHA-1 hash function exclusively to compute message digests.
The main problem with DSA is the fixed subgroup size (the order of the generator element), which limits the security to around only 80 bits. Hardware attacks can be menacing to some implementations of DSS. However, it is widely used and accepted as a good algorithm.

ElGamal

The ElGamal is a public key cipher - an asymmetric key encryption algorithm for public-key cryptography which is based on the Diffie-Hellman key agreement. ElGamal is the predecessor of DSA.

ECDSA

Elliptic Curve DSA (ECDSA) is a variant of the Digital Signature Algorithm (DSA) which operates on elliptic curve groups. As with Elliptic Curve Cryptography in general, the bit size of the public key believed to be needed for ECDSA is about twice the size of the security level, in bits.

XTR

XTR is an encryption algorithm for public-key encryption. XTR is a novel method that makes use of traces to represent and calculate powers of elements of a subgroup of a finite field. It is based on the primitive underlying the very first public key cryptosystem, the Diffie-Hellman key agreement protocol.
From a security point of view, XTR security relies on the difficulty of solving discrete logarithm related problems in the multiplicative group of a finite field. Some advantages of XTR are its fast key generation (much faster than RSA), small key sizes (much smaller than RSA, comparable with ECC for current security settings), and speed (overall comparable with ECC for current security settings).

Differences between symmetric and asymmetric encryption algorithms

Symmetric encryption algorithms encrypt and decrypt with the same key. Main advantages of symmetric encryption algorithms are its security and high speed. Asymmetric encryption algorithms encrypt and decrypt with different keys. Data is encrypted with a public key, and decrypted with a private key. Asymmetric encryption algorithms (also known as public-key algorithms) need at least a 3,000-bit key to achieve the same level of security of a 128-bit symmetric algorithm. Asymmetric algorithms are incredibly slow and it is impractical to use them to encrypt large amounts of data. Generally, symmetric encryption algorithms are much faster to execute on a computer than asymmetric ones. In practice they are often used together, so that a public-key algorithm is used to encrypt a randomly generated encryption key, and the random key is used to encrypt the actual message using a symmetric algorithm. This is sometimes called hybrid encryption.

Strength of Encryption Algorithms

Strong encryption algorithms should always be designed so that they are as difficult to break as possible. In theory, any encryption algorithm with a key can be broken by trying all possible keys in sequence. If using brute force to try all keys is the only option, the required computing power increases exponentially with the length of the key. A 32-bit key takes 232 (about 109) steps. This is something anyone can do on his/her home computer. An encryption algorithm with 56-bit keys, such as DES, requires a substantial effort, but using massive distributed systems requires only hours of computing. In 1999, a brute-force search using a specially designed supercomputer and a worldwide network of nearly 100,000 PCs on the Internet, found a DES key in 22 hours and 15 minutes. It is currently believed that keys with at least 128 bits (as in AES, for example) will be sufficient against brute-force attacks into the foreseeable future.
However, key length is not the only relevant issue. Many encryption algorithms can be broken without trying all possible keys. In general, it is very difficult to design ciphers that could not be broken more effectively using other methods.
The keys used in public-key encryption algorithms are usually much longer than those used in symmetric encryption algorithms. This is caused by the extra structure that is available to the cryptanalyst. There the problem is not that of guessing the right key, but deriving the matching private key from the public key. In the case of RSA encryption algorithm, this could be done by factoring a large integer that has two large prime factors. In the case of some other cryptosystems, it is equivalent to computing the discrete logarithm modulo a large integer (which is believed to be roughly comparable to factoring when the moduli is a large prime number).


ENCRYPTION AND DECRYPTION ALGORITHM


ENCRYPTION AND DECRYPTION ALGORITHM

Encryption  is a  process of coding information which could either be a file or  mail message  in into cipher text  a form unreadable without a decoding key in order to prevent anyone except the intended recipient from reading that data. Decryption is the reverse process of converting encoded data to its original un-encoded form, plaintext.
A key  in cryptography is a long sequence of bits used by encryption / decryption algorithms. For example, the following represents a hypothetical 40-bit key:

00001010 01101001 10011110 00011100 01010101
A given encryption algorithm takes the original message, and a key, and alters the original message mathematically based on the key's bits to create a new encrypted message. Likewise, a decryption algorithm takes an encrypted message and restores it to its original form using one or more keys. An Article by your Guide Bradley Mitchell
 When a user encodes a file, another user cannot decode and read the file without the decryption key. Adding a digital signature, a form of personal authentication, ensures the integrity of the original message
“To encode plaintext, an encryption key is used to impose an encryption algorithm onto the data. To decode cipher, a user must possess the appropriate decryption key. A decryption key consists of a random string of numbers, from 40 through 2,000 bits in length. The key imposes a decryption algorithm onto the data. This decryption algorithm reverses the encryption algorithm, returning the data to plaintext. The longer the encryption key is, the more difficult it is to decode. For a 40-bit encryption key, over one trillion possible decryption keys exist.
There are two primary approaches to encryption: symmetric and public-key. Symmetric encryption is the most common type of encryption and uses the same key for encoding and decoding data. This key is known as a session key. Public-key encryption uses two different keys, a public key and a private key. One key encodes the message and the other decodes it. The public key is widely distributed while the private key is secret.
Aside from key length and encryption approach, other factors and variables impact the success of a cryptographic system. For example, different cipher modes, in coordination with initialization vectors and salt values, can be used to modify the encryption method. Cipher modes define the method in which data is encrypted. The stream cipher mode encodes data one bit at a time. The block cipher mode encodes data one block at a time. Although block cipher tends to execute more slowly than stream cipher, block”
Platform Builder for Microsoft Windows CE 5.0

BACKGROUND OF ENCRYPTION AND DECRYPTION ALGORITHM  
 
CRYPTOGRAPHY is an algorithmic process of converting a plain text or clear text message to a cipher text or cipher message based on an algorithm that both the sender and receiver know, so that the cipher text message can be returned to its original, plain text form. In its cipher form, a message cannot be read by anyone but the intended receiver. The act of converting a plain text message to its cipher text form is called enciphering. Reversing that act (i.e., cipher text form to plain text message) is deciphering. Enciphering and deciphering are more commonly referred to  as encryption and decryption, respectively.

There are a number of algorithms for performing encryption and decryption, but comparatively few such algorithms have stood the test of time. The most successful algorithms use a key. A key is simply a parameter to the algorithm that allows the encryption and decryption process to occur. There are many modern key-based cryptographic techniques . These are divided into two classes: symmetric and asymmetric (also called public/private) key cryptography. In symmetric key cryptography, the same key is used for both encryption and decryption. In asymmetric key cryptography, one key is used for encryption and another, mathematically related key, is used for decryption.

TYPES OF CRYPTOGRAPHIC ALGORITHMS

There are several ways of classifying cryptographic algorithms. For purposes of this report  they will be categorized based on the number of keys that are employed for encryption and decryption, and further defined by their application and use. The following are the three types of Algorithm that are disscused
·         Secret Key Cryptography (SKC): Uses a single key for both encryption and decryption
·         Public Key Cryptography (PKC): Uses one key for encryption and another for decryption
·         Hash Functions: Uses a mathematical transformation to irreversibly "encrypt" information

            Gary c. Kessler May 1998
            (26 September 2005)


Symmetric Key Cryptography

The most widely used symmetric key cryptographic method is the Data Encryption Standard (DES) , published in 1977 by the National Bureau of Standards.  DES It is still the most widely used symmetric-key approach. It  uses a fixed length, 56-bit key and an efficient algorithm to quickly encrypt and decrypt messages. It can be easily implemented in hardware, making the encryption and decryption process even faster. In general, increasing the key size makes the system more secure. A variation of DES, called Triple-DES or DES-EDE (encrypt-decrypt-encrypt), uses three applications of DES and two independent DES keys to produce an effective key length of 168 bits [ANSI 85].
The International Data Encryption Algorithm (IDEA) was invented by James Massey and Xuejia Lai of ETH Zurich, Switzerland in 1991. IDEA uses a fixed length, 128-bit key (larger than DES but smaller than Triple-DES). It is also faster than Triple-DES. In the early 1990s, Don Rivest of RSA Data Security, Inc., invented the algorithms RC2 and RC4. These use variable length keys and are claimed to be even faster than IDEA. However, implementations may be exported from the U.S. only if they use key lengths of 40 bits or fewer.
Despite the efficiency of  symmetric key cryptography , it has a fundamental weak spot-key management. Since the same key is used for encryption and decryption, it must be kept secure. If an adversary knows the key, then the message can be decrypted. At the same time, the key must be available to the sender and the receiver and these two parties may be physically separated. Symmetric key cryptography transforms the problem of transmitting messages securely into that of transmitting keys securely. This is an improvement , because keys are much smaller than messages, and the keys can be generated beforehand. Nevertheless, ensuring that the sender and receiver are using the same key and that potential adversaries do not know this key remains a major stumbling block. This is referred to as the key management problem.

Public/Private Key Cryptography

Asymmetric key cryptography overcomes the key management problem by using different encryption and decryption key pairs. Having knowledge of one key, say the encryption key, is not sufficient enough to determine the other key - the decryption key. Therefore, the encryption key can be made public, provided the decryption key is held only by the party wishing to receive encrypted messages (hence the name public/private key cryptography). Anyone can use the public key to encrypt a message, but only the recipient can decrypt it.
RSA  is a widely used public/private key algorithm is, named after the initials of its inventors, Ronald L. Rivest, Adi Shamir, and Leonard M. Adleman [RSA 91]. It depends on the difficulty of factoring the product of two very large prime numbers. Although used for encrypting whole messages, RSA is much less efficient than symmetric key algorithms such as DES. ElGamal is another public/private key algorithm [El Gamal 85]. This uses a different arithmetic algorithm than RSA, called the discrete logarithm problem.
The mathematical relationship between the public/private key pair permits a general rule: any message encrypted with one key of the pair can be successfully decrypted only with that key's counterpart. To encrypt with the public key means you can decrypt only with the private key. The converse is also true - to encrypt with the private key means you can decrypt only with the public key.
 Salomaa 96.

Hash functions

 “Is a type of one-way function this  are fundamental for much of cryptography. A one way function - is a function that is easy to calculate but hard to invert. It is difficult to calculate the input to the function given its output. The precise meanings of "easy" and "hard" can be specified mathematically. With rare exceptions, almost the entire field of public key cryptography rests on the existence of one-way functions
In this application, functions are characterized and evaluated in terms of their ability to withstand attack by an adversary. More specifically, given a message x, if it is computationally infeasible to find a message y not equal to x such that H(x) = H(y) then H is said to be a weakly collision-free hash function. A strongly collision-free hash function H is one for which it is computationally infeasible to find any two messages x and y such that H(x) = H(y).
The requirements for a good cryptographic hash function are stronger than those in many other applications (error correction and audio identification not included). For this reason, cryptographic hash functions make good stock hash functions--even functions whose cryptographic security is compromised, such as MD5 and SHA-1. The SHA-2 algorithm, however, has no known compromises”
hash function ca also be referred to as a function  with certain additional security properties to make it suitable for use as a primitive in various information security applications, such as authentication and message integrity. It  takes a long string (or message) of any length as input and produces a fixed length string as output, sometimes termed a message digest or a digital fingerprint.

A hash function at work
A hash function at work
In various standards and applications, the two most-commonly used hash functions are MD5 and SHA-1; however, as of 2005, security flaws have been identified in both algorithms.

From Wikipedia, the free encyclopaedia.



 Cryptographic hash function
 
Hash functions (a type of one-way function) are fundamental for much of cryptography. In this application, functions are characterized and evaluated in terms of their ability to withstand attack by an adversary. More specifically, given a message x, if it is computationally infeasible to find a message y not equal to x such that H(x) = H(y) then H is said to be a weakly collision-free hash function. A strongly collision-free hash function H is one for which it is computationally infeasible to find any two messages x and y such that H(x) = H(y).
The requirements for a good cryptographic hash function are stronger than those in many other applications (error correction and audio identification not included). For this reason, cryptographic hash functions make good stock hash functions--even functions whose cryptographic security is compromised, such as MD5 and SHA-1. The SHA-2 algorithm, however, has no known compromises
 Fig 1 illustrates the proper and intended used of public/private key cryptography for sending confidential messages. In the illustration, a user, Bob, has a public/private key pair. The public portion of that key pair is placed in the public domain (for example in a Web server). The private portion is guarded in a private domain, for example, on a digital key card or in a password-protected file.
Figure 1: Proper Use of Public Key Cryptography
For Alice to send a secret message to Bob, the following process needs to be followed:
  1. Alice passes the secret message and Bob's public key to the appropriate encryption algorithm to construct the encrypted message.
  2. Alice transmits the encrypted message (perhaps via e-mail) to Bob.
  3. Bob decrypts the transmitted, encrypted message with his private key and the appropriate decryption algorithm.
Bob can be assured that Alice's encrypted secret message was not seen by anyone else since only his private key is capable of decrypting the message

Both Are Used Together

Secret key and public key systems are often used together, such as the AES secret key and the RSA public key. The secret key method provides the fastest decryption, and the public key method provides a convenient way to transmit the secret key. This is called a "digital envelope." For example, the PGP e-mail encryption program uses one of several public key methods to send the secret key along with the message that has been encrypted with that secret key (see PGP).

Get Faster - Get Stronger

 
It has been said that any encryption code can be broken given enough time to compute all permutations. However, if it takes months to break a code, the war could already be lost, or the thief could have long absconded with the money from the forged financial transaction. As computers get faster, to stay ahead of the game, encryption algorithms have to become stronger by using longer keys and more clever techniques.


Encryption and Decryption in PHP part : 2

Encryption and Decryption in PHP


<?php

$key = 'Your Key';
$string = 'My String'; // note the spaces

$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));

$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");

echo 'Encrypted:' . "\n";
var_dump($encrypted);

echo "\n";

echo 'Decrypted:' . "\n";
var_dump($decrypted); // spaces are preserved

?>

Output : 

Origional : 'My String'

Encrypted:
string 'X7zPEx/hl2aMvBrK2+V3XJtqvQssSiYUQWTFyHlbjmQ=' (length=44)
Decrypted:
string 'My String' (length=9)

Simple PHP encrypt and decrypt part : 1

/**
* simple method to encrypt or decrypt a plain text string
* initialization vector(IV) has to be the same when encrypting and decrypting
* PHP 5.4.9
*
* this is a beginners template for simple encryption decryption
* before using this in production environments, please read about encryption
*
* @param string $action: can be 'encrypt' or 'decrypt'
* @param string $string: string to encrypt or decrypt
*
* @return string
*/
function encrypt_decrypt($action, $string) {
$output = false;

$encrypt_method = "AES-256-CBC";
$secret_key = 'This is my secret key';
$secret_iv = 'This is my secret iv';

// hash
$key = hash('sha256', $secret_key);

// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);

if( $action == 'encrypt' ) {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
}
else if( $action == 'decrypt' ){
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}

return $output;
}

$plain_txt = "This is my plain text";
echo "Plain Text = $plain_txt\n";

$encrypted_txt = encrypt_decrypt('encrypt', $plain_txt);
echo "Encrypted Text = $encrypted_txt\n";

$decrypted_txt = encrypt_decrypt('decrypt', $encrypted_txt);
echo "Decrypted Text = $decrypted_txt\n";

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

echo "\n";

md5 Encryption/Decryption


md5

(PHP 4, PHP 5)
md5Calculate the md5 hash of a string

Description

string md5 ( string $str [, bool $raw_output = false ] )
Calculates the MD5 hash of str using the » RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash.

Parameters

str
The string. 

raw_output
 
If the optional raw_output is set to TRUE, then the md5 digest is instead returned in raw binary format with a length of 16.

Return Values

Returns the hash as a 32-character hexadecimal number.




Example #1 A md5() example
<?php
$str 
'apple';

if (
md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
    echo 
"Would you like a green or red apple?";
}
?>

AUTO-APPROVE TIME OFF REQUESTS (phpcode)

<?php
// EXAMPLE: AUTO-APPROVE TIME OFF REQUESTS
//
// This code example illustrates how to listen for newly created requests for time off, then
// automatically approve them (this is great for organizations that have a more flexible time
// off policy). This script listens for a WebHook event, then connects to the site via the REST
// API to get the details and modify the details of the request.
//
// More on WebHooks: http://developers.tribehr.com/api/webhook-event-notification/
// More on the REST Api: http://developers.tribehr.com/api/api-introduction/
//
// PHP API Wrapper: https://github.com/TribeHR/TribeHR-PHP-Client
// Set your TribeHR credentials
define('SUBDOMAIN', ''); // Your TribeHR Sub Domain
define('USER', ''); // The username of an Administrator
define('KEY', ''); // The API KEY of the administrator above
// Include the API Wrapper
require('./TribeHR-PHP-Client/TribeHR.php');
// Let's only process the payload if we're going to actually be getting
// a LeaveRequest. Note - this logic can be easily extende to create a script that
// can handle multiple different WebHook types.
if(isset($_POST['object_id']) && isset($_POST['object']) && $_POST['object'] == 'LeaveRequest')
{
// Create my connection to the site using the API Wrapper
$TribeHRConnection = new TribeHRConnector(SUBDOMAIN, USER, KEY);
// Get the specific Leave Request, as specified by the WebHook data
$id = intval($_POST['object_id']);
$tc = $TribeHRConnection->sendRequest('/leave_requests/'.$id.'.xml', 'GET');
// Create the new request data, based on the old request. Some interesting constraints
// caused by the current API version:
// - date_start and date_end exped m/d/Y format, but the API returns Y-m-d
// - the API requires a complete data object, so all fields must be specified
// - the status APPROVED == 1
$old_request = simplexml_load_string($tc->response);
$new_request = array(
'id' => (string) $old_request->leave_request['id'],
'comments' => (string) $old_request->leave_request['comments'] . "\nAuto-Approved",
'date_start' => date('m/d/Y', strtotime($old_request->leave_request['date_start'])),
'date_end' => date('m/d/Y', strtotime($old_request->leave_request['date_end'])),
'days' => (string) $old_request->leave_request['days'],
'leave_type_id' => (string) $old_request->leave_request['leave_type_id'],
'user_id' => (string) $old_request->leave_request['user_id'],
'status' => 1,
);
// Submit the new data
$tc = $TribeHRConnection->sendRequest('/leave_requests/'.$id.'.xml', 'PUT', $new_request);
// Let's echo our the response for good measure
echo htmlentities($tc->response);
}
else
{
// Since there wasn't a valid payload, let's echo a message out
echo 'This script listens for TribeHR WebHooks to auto-approve vacation requests';
}
?>

Monday 25 August 2014

Marquee style in different manner with PHP and MySql

marquee tag is used for more purpose, like top news publishing with marquee scrolling and more frequently publishing news or some other all things are scroll in a particular area, for that here we are using the marquee tag.

STOP / START

Marquee start and stop is the one main function most of us searching this thing, how is it happens on mouse hover. see the code.
<marquee behavior="scroll" onmouseover="this.stop();" onmouseout="this.start();">
</
marquee>

onmouseover="this.stop();" for stop the marquee content on on mouse over, onmouseout="this.start();" for start the marquee tag content on mouse out.

MARQUEE DIRECTION 

Marquee direction is for make the marquee move direction, the moving of marquee tag is move towards to which direction, like left to right, or right to left like that. for that we are using that marquee direction tag. see the code.
<marquee behavior="scroll" direction="right/left/up/down" onmouseover="this.stop();" onmouseout="this.start();">
</marquee>

choose any one direction in the above direction like left or right or up or down any one direction.

MARQUEE SPEED

Marquee  speed how reduce and increase the speed of marquee tag moving. see the code.
<marquee behavior="scroll" scrollamount="5" direction="right" onmouseover="this.stop();" onmouseout="this.start();">
</marquee>

that is scrollamount="5" we can give any number value for that, when you increase the value of scrollamount the speed will be increased, when you are reducing the scrollamount the speed will be decreased.

PHP and Mysql FETCH FROM DATABASE

<?php
$con=mysql_connect('localhost','root','');
$db=mysql_select_db('2my4edge',$con);
?>

Database name --> 2my4edge
table name --> marquee
column names --> id, feeds

<div class="main">
<?php
$fetch=mysql_query("select * from marquee limit 5");
if(mysql_num_rows($fetch))
{
?>
<marquee behavior="scroll" scrollamount="2" direction="up" onmouseover="this.stop();" onmouseout="this.start();">
<ul class="ulclass" >
<?php
while($row=mysql_fetch_array($fetch))
{
$id=$row['id'];
$feed=$row['feeds'];
?>
<li class="liclass">
<?php echo $feed; ?>
<?php } ?>
</li>
<?php } ?>
</ul>

</marquee>
</div>
you can clear with the above coding, just fetch data from the database, which is from marquee table, * astrick is for select all the field from the table name. and make the coding with simple.

Praphull's Marquees

Type this:

<MARQUEE>Your text</MARQUEE>

And you get this.

Your text



Type this:

<MARQUEE DIRECTION=RIGHT>Your text</MARQUEE>

And you get this.

Your text



Type this:

<MARQUEE BEHAVIOR=ALTERNATE>Your text</MARQUEE>

And you get this.

Your text



Type this:

<CENTER><MARQUEE BEHAVIOR=ALTERNATE WIDTH="40%">Your text</MARQUEE></CENTER>

And you get this.

Your text




Type this.

<MARQUEE DIRECTION=DOWN HEIGHT=60>Your text</MARQUEE>

And you get this.

Your text



Type this.

<MARQUEE DIRECTION=UP HEIGHT=50>Your text</MARQUEE>

And you get this.

Your text



Type this.

<MARQUEE DIRECTION=DOWN HEIGHT=50 BEHAVIOR=ALTERNATE>Your text</MARQUEE>

And you get this.

Your text

Replace text with animation or pictures.


Type this.

<MARQUEE><IMG SRC="Your picture URL"></MARQUEE>

And you get this.

DOG



Type this.

<MARQUEE DIRECTION=UP HEIGHT=70 BEHAVIOR=ALTERNATE><IMG SRC="Your picture URL here"> </MARQUEE>

And you get this.

ball



Type this.

<MARQUEE DIRECTION=RIGHT WIDTH="50%"><IMG SRC="Your picture URL here"></MARQUEE> <MARQUEE WIDTH="50%"><IMG SRC="Your picture URL here"></MARQUEE>

And you get this.

gif gif

Extra Stuff


Use the BGCOLOR attribute to change the background color of a marquee, specify the color by name or hexadecimal value for the color you want to use.

Type this:

<MARQUEE BEHAVIOR="SCROLL" DIRECTION="LEFT" SCROLLAMOUNT="2" SCROLLDELAY="60" BGCOLOR="RED">Your text here</MARQUEE>

And you get this.

Your text here