Monday, October 20, 2008

using secure random and message direct to generate random nad unique number

The following method uses SecureRandom and MessageDigest :

  • upon startup, initialize SecureRandom (this may be a lengthy operation)
  • when a new identifier is needed, generate a random number using SecureRandom
  • create a MessageDigest of the random number
  • encode the byte[] returned by the MessageDigest into some acceptable textual form
  • check if the result is already being used ; if it is not already taken, it is suitable as a unique identifier
The MessageDigest class is suitable for generating a "one-way hash" of arbitrary data. (Note that hash values never uniquely identify their source data, since different source data can produce the same hash value. The value of hashCode, for example, does not uniquely identify its associated object.) A MessageDigest takes any input, and produces a String which :
  • is of fixed length
  • does not allow the original input to be easily recovered (in fact, this is very hard)
  • does not uniquely identify the input ; however, similar input will produce dissimilar message digests
MessageDigest is often used as a checksum, for verifying that data has not been altered since its creation.

Example

import java.security.SecureRandom;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class GenerateId {

public static void main (String... arguments) {
try {
//Initialize SecureRandom
//This is a lengthy operation, to be done only upon
//initialization of the application
SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");

//generate a random number
String randomNum = new Integer( prng.nextInt() ).toString();

//get its digest
MessageDigest sha = MessageDigest.getInstance("SHA-1");
byte[] result = sha.digest( randomNum.getBytes() );

System.out.println("Random number: " + randomNum);
System.out.println("Message digest: " + hexEncode(result) );
}
catch ( NoSuchAlgorithmException ex ) {
System.err.println(ex);
}
}

/**
* The byte[] returned by MessageDigest does not have a nice
* textual representation, so some form of encoding is usually performed.
*
* This implementation follows the example of David Flanagan's book
* "Java In A Nutshell", and converts a byte array into a String
* of hex characters.
*
* Another popular alternative is to use a "Base64" encoding.
*/

static private String hexEncode( byte[] aInput){
StringBuilder result = new StringBuilder();
char[] digits = {'0', '1', '2', '3', '4','5','6','7','8','9','a','b','c','d','e','f'};
for ( int idx = 0; idx < aInput.length; ++idx) {
byte b = aInput[idx];
result.append( digits[ (b&0xf0) >> 4 ] );
result.append( digits[ b&0x0f] );
}
return result.toString();
}
}


Example run :

>java -cp . GenerateId
Random number: -1103747470
Message digest: c8fff94ba996411079d7114e698b53bac8f7b037

generate unique ID using UUID utility in Java5

mport java.util.UUID;


public class UniqueID {

public static void main(String args[]){
UUID one = UUID.randomUUID();
UUID two = UUID.randomUUID();

System.out.println(one);

System.out.println(two);



}

}

to generate random characters

link

public class RandomCharacters {

private static void doRandomCharacters() {

double randomNumber;
double randomNumberSetup;
char randomCharacter;

System.out.println("----------------------------------------------------------------------");

for (int i = 0; i < 10; i++) {
randomNumber = Math.random();
randomNumberSetup = (randomNumber * 26 + 'a');
randomCharacter = (char) randomNumberSetup;
System.out.print(randomCharacter + ": ");
switch(randomCharacter) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u': System.out.print("vowel");
break;
case 'y':
case 'w': System.out.print("sometimes a vowel");
break;
default: System.out.print("consonant");
}
System.out.println(" - Random number was (" + randomNumber + ")");
}

System.out.println("----------------------------------------------------------------------");
System.out.println("\n");
}


/**
* Sole entry point to the class and application.
* @param args Array of String arguments.
*/
public static void main(String[] args) {
doRandomCharacters();
}

}

Thursday, October 16, 2008

what characters are valid in url?

The specification for URLs, RFC1738, limits the use of allowed characters to only a limited subset of the US-ASCII character set (2.2 URL Character Encoding Issues):

"The lower case letters "a"--"z", digits, and the characters plus ("+"), period("."), and hyphen ("-") are allowed.... In addition, octets may be encoded by a character triplet consisting of the character "%" followed by the two hexadecimal digits (from"0123456789ABCDEF") which forming (sic) the hexadecimal value of the octet. (The characters "abcdef" may also be used in hexadecimal encodings.)"

To insert, for example, the French accented à, you would use %E0 instead of the letter.

Tuesday, October 14, 2008

snake game

http://javaboutique.internet.com/Snake/source.html

When the snake game executes it looks like this....click here

parsing a string

study:

You are to create a console application that accepts exactly one command-line argument. If it doesn’t receive the argument, the application must display an error message and exit. The application must parse the text input and output the number of times each letter of the alphabet occurs in the text. Case sensitivity is not required.

For example, if the command-line argument is “baaad” the displayed result must be:

There are 3 A's
There are 1 B's
There are 0 C's
There are 1 D's
There are 0 E's
There are 0 F's
etc...


Result: In this we use Stream Tokenizer.


mport java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;


public class Class1 {

public static void main(String[] av) throws IOException {
StreamTokenizer tf = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
String s = null;
char a[] = {'A', 'B', 'C', 'D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R',
'S','T','U','V','W','X','Y','Z'};

int count = 0;
int i, r=0,m=0;

while ((i = tf.nextToken()) != StreamTokenizer.TT_EOF) {
switch (i) {
/* case StreamTokenizer.TT_EOF:
System.out.println("End of file");
break;
case StreamTokenizer.TT_EOL:
System.out.println("End of line");
break;
case StreamTokenizer.TT_NUMBER:
System.out.println("Number " + tf.nval);
break;*/

case StreamTokenizer.TT_WORD:
s = tf.sval.toUpperCase();
System.out.println("Word, length " + tf.sval.length() + " " );
while(r<>

{if (s.charAt(p) == a[r])

count++;

}

System.out.println("There are " +count +a[r]);

count=0; r++; }

break;

default:

System.out.println("What is it? i = " + i);

} } } }

Thursday, October 9, 2008

requirements for key generator

new class KeyGenerator
lives in a package: edu.gvsu.cri.utils

Research:
1. valid web characters for the url address
2. random key of n characters where n is the parameter of method
3. research methods of randomness i.e. method based on time stand.