java source code

7
Java Source Code testDES.java import java.io.*; import java.security.*; import java.math.*; import cryptix.util.core.BI; import cryptix.util.core.ArrayUtil; import cryptix.util.core.Hex; import 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("01010101010101010102030405060708090A0B0C0D0E0F101112 131415161718")); // 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);

Upload: mani-kandan

Post on 04-Mar-2015

290 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java Source Code

Java Source Code

testDES.java

import java.io.*;import java.security.*;import java.math.*;import cryptix.util.core.BI;import cryptix.util.core.ArrayUtil;import cryptix.util.core.Hex;import 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.7bPrintStream output1 = new PrintStream(outFile1);

// convert a string to a DES key and print out the resultRawSecretKey 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 stringCipher des=Cipher.getInstance("DES/ECB/NONE","Cryptix");des.initEncrypt(key2);byte[] ciphertext =

des.crypt(Hex.fromString("01010101010101010102030405060708090A0B0C0D0E0F101112131415161718"));

// 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

Page 2: Java Source Code

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 = 32Ciphertext for DES encryption = Multi-Precision Integer 254 bits long... sign: Positive magnitude: 3A2EAD12F475D82C 1FC97BB9A6D955E1 EA5541946BB4F2E6 F29555A6E8F1FB3C

plaintext.length = 32Plaintext for DES encryption = Multi-Precision Integer 249 bits long... sign: Positive magnitude: 0101010101010101 0102030405060708 090A0B0C0D0E0F10 1112131415161718

RSA

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

import javax.crypto.Cipher;

Page 3: Java Source Code

public class MainClass {  public static void main(String[] args) throws Exception {    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    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(privKeySpec);

    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 java.security.*; import javax.crypto.*; import javax.crypto.spec.*; import 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);

Page 4: Java Source Code

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 java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.UnsupportedEncodingException;

Page 5: Java Source Code

import 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 java.math.BigInteger;import java.security.KeyFactory;import java.security.KeyPair;import java.security.KeyPairGenerator;import 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));

Page 6: Java Source Code

    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);  }}