tag:blogger.com,1999:blog-79868569352124735202018-05-27T18:01:22.240-07:00Cryptography for Safeiroshanhttp://www.blogger.com/profile/13307096887194973271noreply@blogger.comBlogger5125tag:blogger.com,1999:blog-7986856935212473520.post-45898951421461859882008-11-11T10:02:00.000-08:002009-01-15T10:00:25.695-08:00RSA algorithmIn a classic cryptosystem in order to make sure that nobody, except the intended recipient, deciphers the message, the people involved had to strive to keep the key secret. In a public-key cryptosystem. The public key cryptography solves one of the most vexing problems of all prior cryptography: the necessity of establishing a secure channel for the exchange of the key.<br /><br />RSA algorithm is a public-key cryptosystem defined by Rivest, Shamir, and Adleman. The scheme is as follows:<br /><br />Let p and q be distinct large primes and let n be their product. Assume that we also computed two integers, d (for decryption) and e (for encryption) such that<br /><br />d * e 1 (mod ø(n))<br /><br />where ø(n) is the number of positive integers smaller than n that have no factor except 1 in common with n<br /><br />The integers n and e are made public, while p, q, and d are kept secret.<br /><br />Let m be the message to be sent, where m is a positive integer less than and relatively prime to n. A plaintext message is easily converted to a number by using either the alphabet position of each letter (a=01, b=02, ..., z=26) or using the standard ASCII table. If necessary (so that m<n), the message can be broken into several blocks.<br /><br />The encoder computes and sends the number<br /><br />m' = m^e mod n<br /><br />To decode, we simply compute<br /><br />e^d mod n<br /><br />Now, since both n and e are public, the question arises: can we compute from them d? The answer: it is possible, if n is factored into prime numbers.<br /><br />The security of RSA depends on the fact that it takes an impractical amount of time to factor large numbers.iroshanhttp://www.blogger.com/profile/13307096887194973271noreply@blogger.com2tag:blogger.com,1999:blog-7986856935212473520.post-51137026484128946782008-11-11T09:51:00.000-08:002008-11-11T09:58:54.222-08:00Triple DES Algorithm<p>Triple DES is simply another mode of DES operation. It takes three 64-bit keys, for an overall key length of 192 bits. In Private Encryptor, you simply type in the entire 192-bit (24 character) key rather than entering each of the three keys individually. The Triple DES DLL then breaks the user provided key into three subkeys, padding the keys if necessary so they are each 64 bits long. The procedure for encryption is exactly the same as regular DES, but it is repeated three times. Hence the name Triple DES. The data is encrypted with the first key, decrypted with the second key, and finally encrypted again with the third key.</p> <center><img src="http://www.tropsoft.com/strongenc/des3p1.gif" alt="" border="0" height="300" width="400" /> </center>Consequently, Triple DES runs three times slower than standard DES, but is much more secure if used properly. The procedure for decrypting something is the same as the procedure for encryption, except it is executed in reverse. Like DES, data is encrypted and decrypted in 64-bit chunks. Unfortunately, there are some weak keys that one should be aware of: if all three keys, the first and second keys, or the second and third keys are the same, then the encryption procedure is essentially the same as standard DES. This situation is to be avoided because it is the same as using a really slow version of regular DES. <p>Note that although the input key for DES is 64 bits long, the actual key used by DES is only 56 bits in length. The least significant (right-most) bit in each byte is a parity bit, and should be set so that there are always an odd number of 1s in every byte. These parity bits are ignored, so only the seven most significant bits of each byte are used, resulting in a key length of 56 bits. This means that the effective key strength for Triple DES is actually 168 bits because each of the three keys contains 8 parity bits that are not used during the encryption process.</p>iroshanhttp://www.blogger.com/profile/13307096887194973271noreply@blogger.com3tag:blogger.com,1999:blog-7986856935212473520.post-90815590890400064402008-11-10T12:45:00.000-08:002008-11-10T12:57:40.090-08:00Java code for Triple DES Algorithmpackage com.davidflanagan.examples.security;<br />import javax.crypto.*;<br />import javax.crypto.spec.*;<br />import java.security.*;<br />import java.security.spec.*;<br />import java.io.*;<br /><br />/**<br /> * This class defines methods for encrypting and decrypting using the Triple<br /> * DES algorithm and for generating, reading and writing Triple DES keys.<br /> * It also defines a main() method that allows these methods to be used<br /> * from the command line.<br /> **/<br />public class TripleDES {<br /> /**<br /> * The program. The first argument must be -e, -d, or -g to encrypt,<br /> * decrypt, or generate a key. The second argument is the name of a file<br /> * from which the key is read or to which it is written for -g. The<br /> * -e and -d arguments cause the program to read from standard input and<br /> * encrypt or decrypt to standard output.<br /> **/<br /> public static void main(String[] args) {<br /> try {<br /> // Check to see whether there is a provider that can do TripleDES<br /> // encryption. If not, explicitly install the SunJCE provider.<br /> try { Cipher c = Cipher.getInstance("DESede"); }<br /> catch(Exception e) {<br /> // An exception here probably means the JCE provider hasn't<br /> // been permanently installed on this system by listing it<br /> // in the $JAVA_HOME/jre/lib/security/java.security file.<br /> // Therefore, we have to install the JCE provider explicitly.<br /> System.err.println("Installing SunJCE provider.");<br /> Provider sunjce = new com.sun.crypto.provider.SunJCE();<br /> Security.addProvider(sunjce);<br /> }<br /><br /> // This is where we'll read the key from or write it to<br /> File keyfile = new File(args[1]);<br /><br /> // Now check the first arg to see what we're going to do<br /> if (args[0].equals("-g")) { // Generate a key<br /> System.out.print("Generating key. This may take some time...");<br /> System.out.flush();<br /> SecretKey key = generateKey();<br /> writeKey(key, keyfile);<br /> System.out.println("done.");<br /> System.out.println("Secret key written to " + args[1] +<br /> ". Protect that file carefully!");<br /> }<br /> else if (args[0].equals("-e")) { // Encrypt stdin to stdout<br /> SecretKey key = readKey(keyfile);<br /> encrypt(key, System.in, System.out);<br /> }<br /> else if (args[0].equals("-d")) { // Decrypt stdin to stdout<br /> SecretKey key = readKey(keyfile);<br /> decrypt(key, System.in, System.out);<br /> }<br /> }<br /> catch(Exception e) {<br /> System.err.println(e);<br /> System.err.println("Usage: java " + TripleDES.class.getName() +<br /> " -d|-e|-g <keyfile>");<br /> }<br /> }<br /><br /> /** Generate a secret TripleDES encryption/decryption key */<br /> public static SecretKey generateKey() throws NoSuchAlgorithmException {<br /> // Get a key generator for Triple DES (a.k.a DESede)<br /> KeyGenerator keygen = KeyGenerator.getInstance("DESede");<br /> // Use it to generate a key<br /> return keygen.generateKey();<br /> }<br /><br /> /** Save the specified TripleDES SecretKey to the specified file */<br /> public static void writeKey(SecretKey key, File f)<br /> throws IOException, NoSuchAlgorithmException, InvalidKeySpecException<br /> {<br /> // Convert the secret key to an array of bytes like this<br /> SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");<br /> DESedeKeySpec keyspec =<br /> (DESedeKeySpec)keyfactory.getKeySpec(key, DESedeKeySpec.class);<br /> byte[] rawkey = keyspec.getKey();<br /><br /> // Write the raw key to the file<br /> FileOutputStream out = new FileOutputStream(f);<br /> out.write(rawkey);<br /> out.close();<br /> }<br /><br /> /** Read a TripleDES secret key from the specified file */<br /> public static SecretKey readKey(File f)<br /> throws IOException, NoSuchAlgorithmException,<br /> InvalidKeyException, InvalidKeySpecException<br /> {<br /> // Read the raw bytes from the keyfile<br /> DataInputStream in = new DataInputStream(new FileInputStream(f));<br /> byte[] rawkey = new byte[(int)f.length()];<br /> in.readFully(rawkey);<br /> in.close();<br /> <br /> // Convert the raw bytes to a secret key like this<br /> DESedeKeySpec keyspec = new DESedeKeySpec(rawkey);<br /> SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");<br /> SecretKey key = keyfactory.generateSecret(keyspec);<br /> return key;<br /> }<br /><br /> /**<br /> * Use the specified TripleDES key to encrypt bytes from the input stream<br /> * and write them to the output stream. This method uses<br /> * CipherOutputStream to perform the encryption and write bytes at the<br /> * same time.<br /> **/<br /> public static void encrypt(SecretKey key, InputStream in, OutputStream out)<br /> throws NoSuchAlgorithmException, InvalidKeyException,<br /> NoSuchPaddingException, IOException<br /> {<br /> // Create and initialize the encryption engine<br /> Cipher cipher = Cipher.getInstance("DESede");<br /> cipher.init(Cipher.ENCRYPT_MODE, key);<br /><br /> // Create a special output stream to do the work for us<br /> CipherOutputStream cos = new CipherOutputStream(out, cipher);<br /><br /> // Read from the input and write to the encrypting output stream<br /> byte[] buffer = new byte[2048];<br /> int bytesRead;<br /> while((bytesRead = in.read(buffer)) != -1) {<br /> cos.write(buffer, 0, bytesRead);<br /> }<br /> cos.close();<br /><br /> // For extra security, don't leave any plaintext hanging around memory.<br /> java.util.Arrays.fill(buffer, (byte) 0);<br /> }<br /><br /> /**<br /> * Use the specified TripleDES key to decrypt bytes ready from the input<br /> * stream and write them to the output stream. This method uses<br /> * uses Cipher directly to show how it can be done without<br /> * CipherInputStream and CipherOutputStream.<br /> **/<br /> public static void decrypt(SecretKey key, InputStream in, OutputStream out)<br /> throws NoSuchAlgorithmException, InvalidKeyException, IOException,<br /> IllegalBlockSizeException, NoSuchPaddingException,<br /> BadPaddingException<br /> {<br /> // Create and initialize the decryption engine<br /> Cipher cipher = Cipher.getInstance("DESede");<br /> cipher.init(Cipher.DECRYPT_MODE, key);<br /><br /> // Read bytes, decrypt, and write them out.<br /> byte[] buffer = new byte[2048];<br /> int bytesRead;<br /> while((bytesRead = in.read(buffer)) != -1) {<br /> out.write(cipher.update(buffer, 0, bytesRead));<br /> }<br /><br /> // Write out the final bunch of decrypted bytes<br /> out.write(cipher.doFinal());<br /> out.flush();<br /> }<br />}iroshanhttp://www.blogger.com/profile/13307096887194973271noreply@blogger.com2tag:blogger.com,1999:blog-7986856935212473520.post-11702149498560273702008-11-10T12:41:00.000-08:002008-11-10T12:42:31.506-08:00AES (Advanced Encription Algorithm )The Advanced Encryption Standard (AES Algorithm) is a computer security standard that became effective on May 26, 2002 by NIST to replace DES. The cryptography scheme is a symmetric block cipher that encrypts and decrypts 128-bit blocks of data. Lengths of 128, 192, and 256 bits are standard key lengths used by AES Algorithm.<br /><br />The algorithm consists of four stages that make up a round which is iterated 10 times for a 128-bit length key, 12 times for a 192-bit key, and 14 times for a 256-bit key. The first stage "SubBytes" transformation is a non-linear byte substitution for each byte of the block. The second stage "ShiftRows" transformation cyclically shifts (permutes) the bytes within the block. The third stage "MixColumns" transformation groups 4-bytes together forming 4-term polynomials and multiplies the polynomials with a fixed polynomial mod (x^4+1). The fourth stage "AddRoundKey" transformation adds the round key with the block of data.<br /><br />In most ciphers, the iterated transform (or round) usually has a Feistel Structure. Typically in this structure, some of the bits of the intermediate state are transposed unchanged to another position (permutation). AES Algorithm does not have a Feistel structure but is composed of three distinct invertible transforms based on the Wide Trial Strategy design method.iroshanhttp://www.blogger.com/profile/13307096887194973271noreply@blogger.com1tag:blogger.com,1999:blog-7986856935212473520.post-16334886798230251142008-06-10T00:58:00.000-07:002008-11-10T12:41:08.584-08:00Simple java code for AES Encryptionimport java.io.*;<br />import java.security.*;<br />import javax.crypto.*;<br /><br />public class MakeEncrypt {<br /><br />public static void main(String args[]) {<br /> if(args.length<2) {<br /> System.out.println("Usage: MakeEncrypt plaintext ciphertext");<br /> return;<br /> }<br /><br /> try {<br /> //Generate a key<br /> Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");<br /> KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");<br /> generator.init(192);<br /> Key encryptionKey = generator.generateKey();<br /> System.out.println("key : " + Utils.toHex(encryptionKey.getEncoded()));<br /><br /> // Open input and out fileencryption pass<br /> FileInputStream fis = new FileInputStream(args[0]);<br /> DataInputStream fdata=new DataInputStream(fis);<br /> FileOutputStream fos = new FileOutputStream(args[1]);<br /><br /> // init encryption<br /> cipher.init(Cipher.ENCRYPT_MODE,encryptionKey);<br /> CipherOutputStream cOut = new CipherOutputStream(fos,cipher);<br /> DataOutputStream dout = new DataOutputStream(cOut);<br /><br /> String s;<br /> while ((s=fdata.readLine())!=null) {<br /> dout.writeBytes(s);<br /> }<br /> <br /> // Save keys and IV<br /> FileOutputStream keyfile = new FileOutputStream("keys");<br /> ObjectOutputStream keyout = new ObjectOutputStream(keyfile);<br /> keyout.writeObject(new String(cipher.getIV()));<br /> keyout.writeObject(new String(encryptionKey.getEncoded()));<br /> System.out.println("Encrypted!");<br /><br /> } catch (Exception e) {<br /> System.out.println(e);<br /> }<br />}<br />}iroshanhttp://www.blogger.com/profile/13307096887194973271noreply@blogger.com4