0% found this document useful (0 votes)
503 views

Java Source Code

This document contains code samples for implementing common cryptographic algorithms and protocols in Java, including DES, RSA, AES, SHA, and Diffie-Hellman key exchange. Code snippets demonstrate generating encryption keys, encrypting/decrypting data, hashing strings, and exchanging keys.

Uploaded by

Mani Kandan
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
503 views

Java Source Code

This document contains code samples for implementing common cryptographic algorithms and protocols in Java, including DES, RSA, AES, SHA, and Diffie-Hellman key exchange. Code snippets demonstrate generating encryption keys, encrypting/decrypting data, hashing strings, and exchanging keys.

Uploaded by

Mani Kandan
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Java Source Code

testDES.java
import import import import import import import java.io.*; java.security.*; java.math.*; cryptix.util.core.BI; cryptix.util.core.ArrayUtil; cryptix.util.core.Hex; cryptix.provider.key.*;

class testDES { public static void main (String[] args) { try { FileOutputStream outFile1 = new FileOutputStream("DES.out"); // Note: PrintStream is deprecated, but still works fine in jdk1.1.7b PrintStream output1 = new PrintStream(outFile1); // convert a string to a DES key and print out the result RawSecretKey key2 = new RawSecretKey("DES",Hex.fromString("3812A419C63BE771")); RawKey rkey = (RawKey) key2; byte[] yval = rkey.getEncoded(); BigInteger Bkey = new BigInteger(yval); String w = cryptix.util.core.BI.dumpString(Bkey); output1.println("The Encryption Key = " + w); // use the DES key to encrypt a string Cipher des=Cipher.getInstance("DES/ECB/NONE","Cryptix"); des.initEncrypt(key2); byte[] ciphertext = des.crypt(Hex.fromString("01010101010101010102030405060708090A0B0C0D0E0F10111 2131415161718")); // print out length and representation of ciphertext output1.print("\n"); output1.println("ciphertext.length = " + ciphertext.length); BigInteger Bciph = new BigInteger(ciphertext); w = cryptix.util.core.BI.dumpString(Bciph); output1.println("Ciphertext for DES encryption = " + w); // decrypt ciphertext des.initDecrypt(key2); ciphertext = des.crypt(ciphertext); output1.print("\n"); output1.println("plaintext.length = " + ciphertext.length); // print out representation of decrypted ciphertext Bciph = new BigInteger(ciphertext);

w = cryptix.util.core.BI.dumpString(Bciph); output1.println("Plaintext for DES encryption = " + w); output1.println(" "); output1.close(); } catch (Exception e) { System.err.println("Caught exception " + e.toString()); } }}

Sample Program Output


DES.out
The Encryption Key = Multi-Precision Integer 62 bits long... sign: Positive magnitude: 3812A419C63BE771 ciphertext.length = 32 Ciphertext for DES encryption = Multi-Precision Integer 254 bits long... sign: Positive magnitude: 3A2EAD12F475D82C 1FC97BB9A6D955E1 EA5541946BB4F2E6 F29555A6E8F1FB3C plaintext.length = 32 Plaintext for DES encryption = Multi-Precision Integer 249 bits long... sign: Positive magnitude: 0101010101010101 0102030405060708 090A0B0C0D0E0F10 1112131415161718

RSA

import import import import import import import

java.math.BigInteger; java.security.KeyFactory; java.security.Security; java.security.interfaces.RSAPrivateKey; java.security.interfaces.RSAPublicKey; java.security.spec.RSAPrivateKeySpec; java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher; public class MainClass {

public static void main(String[] args) throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvid er()); byte[] input = new byte[] { (byte) 0xbe, (byte) 0xef }; Cipher cipher = Cipher.getInstance("RSA/None/NoPadding", "BC"); KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC"); RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger( "12345678", 16), new BigInteger("11", 16)); RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(new BigInteger( "12345678", 16), new BigInteger("12345678", 16)); RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec ); RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privKe ySpec); cipher.init(Cipher.ENCRYPT_MODE, pubKey); byte[] cipherText = cipher.doFinal(input); System.out.println("cipher: " + new String(cipherText)); cipher.init(Cipher.DECRYPT_MODE, privKey); byte[] plainText = cipher.doFinal(cipherText); System.out.println("plain : " + new String(plainText)); } }

aes

import import import import

java.security.*; javax.crypto.*; javax.crypto.spec.*; java.io.*;

/** * This program generates a AES key, retrieves its raw bytes, and * then reinstantiates a AES key from the key bytes. * The reinstantiated key is used to initialize a AES cipher for * encryption and decryption. */ public class AES { /** * Turns array of bytes into string * * @param buf Array of bytes to convert to hex string * @return Generated hex string */ public static String asHex (byte buf[]) { StringBuffer strbuf = new StringBuffer(buf.length * 2); int i;

for (i = 0; i < buf.length; i++) { if (((int) buf[i] & 0xff) < 0x10) strbuf.append("0"); strbuf.append(Long.toString((int) buf[i] & 0xff, 16)); } return strbuf.toString(); } public static void main(String[] args) throws Exception { String message="This is just an example"; // Get the KeyGenerator KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); // 192 and 256 bits may not be available // Generate the secret key specs. SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); // Instantiate the cipher Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal((args.length == 0 ? "This is just an example" : args[0]).getBytes()); System.out.println("encrypted string: " + asHex(encrypted)); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] original = cipher.doFinal(encrypted); String originalString = new String(original); System.out.println("Original string: " + originalString + " " + asHex(original)); } }

Sha
import import import import import java.io.BufferedReader; java.io.IOException; java.io.InputStreamReader; java.io.UnsupportedEncodingException; java.security.NoSuchAlgorithmException;

public class Ex01 { public static void main(String[] args) throws IOException { BufferedReader userInput = new BufferedReader (new InputStreamReader(System.in)); System.out.println("Enter string:"); String rawString = userInput.readLine(); try { System.out.println("SHA1 hash of string: " + AeSimpleSHA1.SHA1(rawString)); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

Implementing the Diffie-Hellman key exchange


import import import import import java.math.BigInteger; java.security.KeyFactory; java.security.KeyPair; java.security.KeyPairGenerator; java.security.SecureRandom;

import javax.crypto.spec.DHParameterSpec; import javax.crypto.spec.DHPublicKeySpec; public class MainClass { public final static int pValue = 47; public final static int gValue = 71; public final static int XaValue = 9; public final static int XbValue = 14; public static void main(String[] args) throws Exception { BigInteger p = new BigInteger(Integer.toString(pValue)); BigInteger g = new BigInteger(Integer.toString(gValue)); BigInteger Xa = new BigInteger(Integer.toString(XaValue)); BigInteger Xb = new BigInteger(Integer.toString(XbValue));

createKey(); int bitLength = 512; // 512 bits SecureRandom rnd = new SecureRandom(); p = BigInteger.probablePrime(bitLength, rnd); g = BigInteger.probablePrime(bitLength, rnd); createSpecificKey(p, g); } public static void createKey() throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("DiffieHellman"); kpg.initialize(512); KeyPair kp = kpg.generateKeyPair(); KeyFactory kfactory = KeyFactory.getInstance("DiffieHellman"); DHPublicKeySpec kspec = (DHPublicKeySpec) kfactory.getKeySpec(kp.getPublic(), DHPublicKeySpec.class); } public static void createSpecificKey(BigInteger p, BigInteger g) throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("DiffieHellman"); DHParameterSpec param = new DHParameterSpec(p, g); kpg.initialize(param); KeyPair kp = kpg.generateKeyPair(); KeyFactory kfactory = KeyFactory.getInstance("DiffieHellman"); DHPublicKeySpec kspec = (DHPublicKeySpec) kfactory.getKeySpec(kp.getPublic(), DHPublicKeySpec.class); } }

You might also like