import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.GregorianCalendar;
import javax.xml.bind.DatatypeConverter;
public class ltpagen {
public String generateLtpaToken(String userName,int duration,String ltpaSecret) {
MessageDigest sha1 = null;
GregorianCalendar creationDate=new GregorianCalendar();
GregorianCalendar expiringDate=new GregorianCalendar();
expiringDate.add(GregorianCalendar.MINUTE, duration);
try {
sha1 = MessageDigest.getInstance( "SHA-1" );
} catch (NoSuchAlgorithmException e) {
e.printStackTrace(System.err);
}
byte[] secretDecoded=DatatypeConverter.parseBase64Binary(ltpaSecret);
byte[] tokenBase=("\000\001\002\003"+getHexRep(creationDate)+getHexRep(expiringDate)+userName).getBytes();
byte[] digest=sha1.digest(concatBytes(tokenBase, secretDecoded));
return DatatypeConverter.printBase64Binary(concatBytes(tokenBase, digest));
}
public static byte[] concatBytes(byte[] arr1, byte[] arr2) {
byte[] result=Arrays.copyOf(arr1, arr1.length+arr2.length);
System.arraycopy(arr2, 0, result, arr1.length, arr2.length);
return result;
}
public static String getHexRep(GregorianCalendar date) {
int timeVal=(int)(date.getTimeInMillis()/1000);
String hex=Integer.toHexString(timeVal).toUpperCase();
if(hex.length()>=8) {
return hex;
} else {
return ("00000000"+hex).substring(-8);
//return String.format("%0"+(8-hex.length())+"d", 0)+hex;
}
}
}
/////////////////// end token generator