Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Connection to databse

Author  Topic 

batmanreturn
Starting Member

3 Posts

Posted - 2006-06-29 : 00:21:04
hi, im totally new to this sql thing.
i have a set of classes here and my objective is to show that they can connect to the database. how am i supposed to do this?

can i post my classes here? theres a lot..

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2006-06-29 : 00:27:17
Please provide more information for us to help you.


KH

Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2006-06-29 : 01:19:41
Want to connect to DB from front end?
http://www.connectionstrings.com/

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

batmanreturn
Starting Member

3 Posts

Posted - 2006-06-29 : 03:07:56
okies.. there are a total of 18 classes and some of them are long.
these are the classes: Agency,Agent, Base64Converter, EncryptUtil, HashFile, HashUtil, IDS, SecureBackup, SecuredClient, SecuredServer, SecuredServerAction, SendSMS, ServiceMain, TgtLocObject, configFile, mDir, mFile, mList.

here goes:
------------
Agency.java
------------
package com.ids;

import java.util.logging.*;

public class Agency extends Thread {
public boolean stop = false;
public boolean terminate = false;
private static mList agentList;
private static HashFile hf;
private static int agentCnt;
private configFile config;
private String logID;
private Logger log;
private Thread[] myThread;

public Agency() {
try {
config = new configFile();
} catch(Exception e) {
System.err.println("Error loading properties file");
return;
}
agentCnt = Integer.parseInt(config.getthreadCnt());

hf = new HashFile("hash.lst", "sysstore","store439", "syskey", "cran1234");
}

public void setLogger (String logString) {
logID = logString;
log = Logger.getLogger(logID);
log.setUseParentHandlers(false);
return;
}

public void stopMonitor() {
stop = true;
Agent ag;
for (int i=0;i<myThread.length;i++) {
if (!(myThread[i] == null )) {
ag = (Agent)myThread[i];
ag.stop = true;
}
}
log.log(Level.INFO,"Stopping Monitor");
}


public void startMonitor() {
if (stop) {
stop = false;
}
log.log(Level.INFO,"Starting Monitor");
}

public int status() {
if (stop)
return 0;
else
return 1;
}

public void run() {
while ( true ) {
if (terminate)
return;
if (!stop) {
//System.out.println( "Thread running..." );

agentList = new mList();
agentList.setList();

if (agentList.isEmpty()) {
//System.out.println ("Empty ");
return;
}

agentList.setCurrent();
myThread = new Thread[agentCnt];
for (int i = 0; i < agentCnt; i++) {
myThread[i] = new Agent(agentList, hf);
myThread[i].start();
}

for (int i = 0; i < agentCnt; i++) {
while (myThread[i].isAlive()) {
try {
Thread.sleep(5000);
} catch ( InterruptedException e ) {
if (!(log==null))
log.log(Level.INFO,"Thread interrupted");
//System.out.println( "Thread interrupted..." );
}
}
}

}
try {
Thread.sleep(Integer.parseInt(config.getcycleInt()));
} catch ( InterruptedException e ) {
if (!(log==null))
log.log(Level.INFO,"Thread interrupted");
//System.out.println( "Thread interrupted..." );
return;
}

}
//System.out.println( "Thread exiting under request..." );
}
}

------------
Agent.java
------------
package com.ids;

import java.util.logging.*;
import javax.swing.*;


public class Agent extends Thread {
private mList aList;
private HashFile hf;
private configFile config;
private SecureBackup sb;
private Logger lg;

public boolean stop;

public Agent (mList list, HashFile hf) {
stop = false;
try {
config = new configFile();
lg = Logger.getLogger(config.getlogName());
lg.setUseParentHandlers(false);
} catch(Exception e) {
System.err.println("Error loading properties file");
return;
}

aList = list;
this.hf = hf;
}

public void run() {
String current = aList.getCurrent();
int comp = -1;
// Use the follwing when sending using Nuova SMS Server
//SendSMS sms = new SendSMS(config.getsmsServer(), config.getsmsDB(), config.getsmsDBid(), config.getsmsDBpw());
int cnt = 0;

while (cnt < 5 && config.getbackupLoc(cnt) != null) {
if (cnt<1)
sb = new SecureBackup(config.getbackupLoc(cnt), config.getBKLOC(),true);
else
sb.addBackupDir(config.getbackupLoc(cnt));
cnt++;
}

while ((current != null) && !stop) {
aList.setNext();

comp = hf.compareFileHash(current);
//System.out.println(current + " ... " + comp);
if ((comp == HashFile.FILE_HASH_MISMATCH) ||
(comp == HashFile.FILE_HASH_NOT_EXIST)) {
int i = 0;
lg.log(Level.INFO, current + " has been compromised!!" +
config.getMessage(comp));
while (config.getsms(i) != null) {
//Use the following when using Nuova SMS Server
//sms.sendMsg(config.getsms(i), (current + " has been compromised! "+ config.getMessage(comp)));

//Use the following when sending to CNC SMS server
System.out.println("Sending sms to " + config.getsms(i) + " by " + i);
SendSMS.sendSMSCNC(config.getsms(i),
current + " has been compromised! "+ config.getMessage(comp));
i++;
}
//JOptionPane.showMessageDialog(null, current + " has been compromised!", "Intruder Alert!", JOptionPane.INFORMATION_MESSAGE);
}
// System.out.println(h.compareFileHash("C:"+File.separatorChar+"IDS"+
// File.separatorChar+"backup"+File.separatorChar+"outfile.txt"));

switch (comp) {
case HashFile.FILE_HASH_MISMATCH:
hf.setQuarantinePath(config.getqPath());
hf.quarantine(current);
sb.restore(current);
break;
case HashFile.FILE_HASH_NOT_EXIST:
hf.setQuarantinePath(config.getqPath());
hf.quarantine(current);
break;
case HashFile.FILE_NOT_EXIST:
sb.restore(current);
break;
}

current = aList.getCurrent();

try {
Thread.sleep( Integer.parseInt(config.getcheckInt()) );
} catch ( InterruptedException e ) {
if (!(lg==null))
lg.log(Level.INFO,"Thread interrupted");
//System.out.println( "Thread interrupted..." );
return;
}
}
if (stop) {
lg.log(Level.INFO,"Stopped thread");
}
//sms = null;
}
}


--------------------
Base64Converter.java
--------------------
package com.ids;

public class Base64Converter
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
{
public static final char [ ] alphabet = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 0 to 7
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 8 to 15
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 16 to 23
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', // 24 to 31
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', // 32 to 39
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', // 40 to 47
'w', 'x', 'y', 'z', '0', '1', '2', '3', // 48 to 55
'4', '5', '6', '7', '8', '9', '+', '/' }; // 56 to 63

//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

public static String encode ( String s )
//////////////////////////////////////////////////////////////////////
{
return encode ( s.getBytes ( ) );
}

public static String encode ( byte [ ] octetString )
//////////////////////////////////////////////////////////////////////
{
int bits24;
int bits6;

char [ ] out
= new char [ ( ( octetString.length - 1 ) / 3 + 1 ) * 4 ];

int outIndex = 0;
int i = 0;

while ( ( i + 3 ) <= octetString.length )
{
// store the octets
bits24 = ( octetString [ i++ ] & 0xFF ) << 16;
bits24 |= ( octetString [ i++ ] & 0xFF ) << 8;
bits24 |= ( octetString [ i++ ] & 0xFF ) << 0;

bits6 = ( bits24 & 0x00FC0000 ) >> 18;
out [ outIndex++ ] = alphabet [ bits6 ];
bits6 = ( bits24 & 0x0003F000 ) >> 12;
out [ outIndex++ ] = alphabet [ bits6 ];
bits6 = ( bits24 & 0x00000FC0 ) >> 6;
out [ outIndex++ ] = alphabet [ bits6 ];
bits6 = ( bits24 & 0x0000003F );
out [ outIndex++ ] = alphabet [ bits6 ];
}

if ( octetString.length - i == 2 )
{
// store the octets
bits24 = ( octetString [ i ] & 0xFF ) << 16;
bits24 |= ( octetString [ i + 1 ] & 0xFF ) << 8;

bits6 = ( bits24 & 0x00FC0000 ) >> 18;
out [ outIndex++ ] = alphabet [ bits6 ];
bits6 = ( bits24 & 0x0003F000 ) >> 12;
out [ outIndex++ ] = alphabet [ bits6 ];
bits6 = ( bits24 & 0x00000FC0 ) >> 6;
out [ outIndex++ ] = alphabet [ bits6 ];

// padding
out [ outIndex++ ] = '=';
}
else if ( octetString.length - i == 1 )
{
// store the octets
bits24 = ( octetString [ i ] & 0xFF ) << 16;

bits6 = ( bits24 & 0x00FC0000 ) >> 18;
out [ outIndex++ ] = alphabet [ bits6 ];
bits6 = ( bits24 & 0x0003F000 ) >> 12;
out [ outIndex++ ] = alphabet [ bits6 ];

// padding
out [ outIndex++ ] = '=';
out [ outIndex++ ] = '=';
}

return new String ( out );
}

}



----------------
EncryptUtil.java
----------------
package com.ids;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;
import java.security.cert.Certificate;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.KeyPair;
import java.security.Key;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.InvalidKeyException;
import java.security.cert.CertificateException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.BadPaddingException;

public class EncryptUtil {

private String keyAlias;
private String keyPass;
private KeyStore keyStore;
private KeyPair keyPair;

public int RSA_SIZE = 256;

public static final int PRIVATE_KEY = 1;
public static final int PUBLIC_KEY = 2;

public EncryptUtil() {
keyPair = null;
keyStore = null;
keyAlias = null;
keyPass = null;
}
public EncryptUtil(String ks, String kp) {
this();
try {
FileInputStream is = new FileInputStream(ks);
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(is, kp.toCharArray());
} catch (KeyStoreException e) {
System.err.println("Key store exception - " + e);
} catch (CertificateException e) {
System.err.println("Key store exception - " + e);
} catch (NoSuchAlgorithmException e) {
System.err.println("No such algorithm - " + e);
} catch (java.io.IOException e) {
System.err.println("IO exception - " + e);
}

}

public void getKeys(String alias, String pass) {
keyAlias = alias;
keyPass = pass;
keyPair = getKey();
}

private KeyPair getKey() {
try {
// Get private key
Key key = keyStore.getKey(keyAlias, keyPass.toCharArray());
if (key instanceof PrivateKey) {
// Get certificate of public key
java.security.cert.Certificate cert = keyStore.getCertificate(keyAlias);

// Get public key
PublicKey publicKey = cert.getPublicKey();

// Return a key pair
return new KeyPair(publicKey, (PrivateKey)key);
}
} catch (UnrecoverableKeyException e) {
System.err.println("Key exception - " + e);
} catch (NoSuchAlgorithmException e) {
System.err.println("No such algorithm - " + e);
} catch (KeyStoreException e) {
System.err.println("Key store exception - " + e);
}
return null;
}

public boolean encryptFile(String infile, String outfile, int keyType) {

try {
FileInputStream fstream = new FileInputStream(infile);

KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(256); // 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 ciphers for AES and RSA
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
Cipher cs = Cipher.getInstance("RSA");
cs.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
byte[] encryptedKey = cs.doFinal(raw);

CipherInputStream cstream = new CipherInputStream(fstream, aesCipher);
FileOutputStream foutstream = new FileOutputStream(outfile);

//write first 256 bytes of encrypted symmetric key
for (int i=0;i<encryptedKey.length;i++)
foutstream.write(encryptedKey[i]);

byte[] b = new byte;
int i = cstream.read(b);
while (i != -1) {
foutstream.write(b, 0, i);
i = cstream.read(b);
}
foutstream.close();
cstream.close();
return true;
} catch (FileNotFoundException e) {
System.err.println("File Not found - " + e);
return false;
} catch (InvalidKeyException e) {
System.err.println("Invalid key - " + e);
return false;
} catch (NoSuchAlgorithmException e) {
System.err.println("No such algorithm - " + e);
return false;
} catch (NoSuchPaddingException e) {
System.err.println("No such padding - " + e);
return false;
} catch (IOException e) {
System.err.println("IO error - " + e);
return false;
} catch (IllegalBlockSizeException e) {
System.err.println("Illegal block size - " + e);
return false;
} catch (BadPaddingException e) {
System.err.println("Bad padding exception - " + e);
return false;
}
}

public boolean encryptFileZip(String infile, String outzip, int keyType) {

try {
FileInputStream fstream = new FileInputStream(infile);

KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(256); // 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 ciphers for AES and RSA
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
Cipher cs = Cipher.getInstance("RSA");
cs.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
byte[] encryptedKey = cs.doFinal(raw);

FileOutputStream foutstream = null;
ZipOutputStream zoutstream = null;

File f = new File(outzip);
if (f.exists()) {
//renames the old zip and creates a new one
f = new File(outzip);
File f2 = new File(outzip + ".tmp");
boolean res = f.renameTo(f2);
//System.out.println("Rename was : " + res);
FileInputStream fin = new FileInputStream(outzip + ".tmp");
foutstream = new FileOutputStream(outzip,false);
zoutstream = new ZipOutputStream(foutstream);
ZipFile zf = new ZipFile(outzip + ".tmp");

Enumeration ez= zf.entries();
InputStream tmpIn;
ZipEntry ze;
int count;
byte[] buf = new byte[1024];
while (ez.hasMoreElements()) {
ze = (ZipEntry)ez.nextElement();
tmpIn = zf.getInputStream(ze);

zoutstream.putNextEntry(ze);
count = tmpIn.read(buf);
while (count != -1) {
zoutstream.write(buf, 0, count);
count = tmpIn.read(buf);
}
}
zf.close();
fin.close();
f2.delete();
}

CipherInputStream cstream = new CipherInputStream(fstream, aesCipher);
if (zoutstream == null) {
foutstream = new FileOutputStream(outzip);
zoutstream = new ZipOutputStream(foutstream);
}
zoutstream.putNextEntry(new ZipEntry(infile));

//write first 256 bytes of encrypted symmetric key
for (int i=0;i<encryptedKey.length;i++)
zoutstream.write(encryptedKey[i]);

byte[] b = new byte;
int i = cstream.read(b);
while (i != -1) {
zoutstream.write(b, 0, i);
i = cstream.read(b);
}
zoutstream.close();
cstream.close();
return true;
} catch (FileNotFoundException e) {
System.err.println("File Not found - " + e);
return false;
} catch (InvalidKeyException e) {
System.err.println("Invalid key - " + e);
return false;
} catch (NoSuchAlgorithmException e) {
System.err.println("No such algorithm - " + e);
return false;
} catch (NoSuchPaddingException e) {
System.err.println("No such padding - " + e);
return false;
} catch (IOException e) {
System.err.println("IO error - " + e);
return false;
} catch (IllegalBlockSizeException e) {
System.err.println("Illegal block size - " + e);
return false;
} catch (BadPaddingException e) {
System.err.println("Bad padding exception - " + e);
return false;
}
}

public boolean encryptFileZip(ArrayList inFileList, String outzip, int keyType) {

try {

KeyGenerator kgen = null;
SecretKey skey = null;
SecretKeySpec skeySpec = null;
Cipher aesCipher = null;
FileInputStream fstream = null;
FileOutputStream foutstream = null;
ZipOutputStream zoutstream = null;
CipherInputStream cstream = null;
File f = new File(outzip);

Cipher cs = Cipher.getInstance("RSA");
cs.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());


foutstream = new FileOutputStream(outzip);
zoutstream = new ZipOutputStream(foutstream);
String infile;

for (int j=0;j<inFileList.size();j++) {
kgen = KeyGenerator.getInstance("AES");
kgen.init(256); // 192 and 256 bits may not be available


// Generate the secret key specs.
skey = kgen.generateKey();
byte[] raw = skey.getEncoded();

skeySpec = new SecretKeySpec(raw, "AES");


// Instantiate the ciphers for AES and RSA
aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec);

byte[] encryptedKey = cs.doFinal(raw);
infile = (String)inFileList.get(j);
zoutstream.putNextEntry(new ZipEntry(infile));

fstream = new FileInputStream(infile);
cstream = new CipherInputStream(fstream, aesCipher);

//write first 256 bytes of encrypted symmetric key
for (int i=0;i<encryptedKey.length;i++)
zoutstream.write(encryptedKey[i]);

byte[] b = new byte;
int i = cstream.read(b);
while (i != -1) {
zoutstream.write(b, 0, i);
i = cstream.read(b);
}
}
zoutstream.close();
cstream.close();
return true;
} catch (FileNotFoundException e) {
System.err.println("File Not found - " + e);
return false;
} catch (InvalidKeyException e) {
System.err.println("Invalid key - " + e);
return false;
} catch (NoSuchAlgorithmException e) {
System.err.println("No such algorithm - " + e);
return false;
} catch (NoSuchPaddingException e) {
System.err.println("No such padding - " + e);
return false;
} catch (IOException e) {
System.err.println("IO error - " + e);
return false;
} catch (IllegalBlockSizeException e) {
System.err.println("Illegal block size - " + e);
return false;
} catch (BadPaddingException e) {
System.err.println("Bad padding exception - " + e);
return false;
}
}

public byte[] encryptString(String clearText, int keyType) {

try {
ByteArrayInputStream bstream = new ByteArrayInputStream(clearText.getBytes());
Cipher cs = Cipher.getInstance("RSA");
if (keyType == PRIVATE_KEY)
cs.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate());
else
cs.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
CipherInputStream cstream = new CipherInputStream(bstream, cs);

ByteArrayOutputStream boutstream = new ByteArrayOutputStream();

byte[] b = new byte;
int i = cstream.read(b);
while (i != -1) {
boutstream.write(b, 0, i);
i = cstream.read(b);
}
return boutstream.toByteArray();
} catch (InvalidKeyException e) {
System.err.println("Invalid key - " + e);
return null;
} catch (NoSuchAlgorithmException e) {
System.err.println("No such algorithm - " + e);
return null;
} catch (NoSuchPaddingException e) {
System.err.println("No such padding - " + e);
return null;
} catch (IOException e) {
System.err.println("IO error - " + e);
return null;
}
}

public String decryptString(byte[] cipherText, int keyType) {

try {
ByteArrayInputStream bstream = new ByteArrayInputStream(cipherText);
Cipher cs = Cipher.getInstance("RSA");
if (keyType == PRIVATE_KEY)
cs.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
else
cs.init(Cipher.DECRYPT_MODE, keyPair.getPublic());
CipherInputStream cstream = new CipherInputStream(bstream, cs);

ByteArrayOutputStream boutstream = new ByteArrayOutputStream();

byte[] b = new byte;
int i = cstream.read(b);
while (i != -1) {
boutstream.write(b, 0, i);
i = cstream.read(b);
}
return boutstream.toString();
} catch (InvalidKeyException e) {
System.err.println("Invalid key - " + e);
return null;
} catch (NoSuchAlgorithmException e) {
System.err.println("No such algorithm - " + e);
return null;
} catch (NoSuchPaddingException e) {
System.err.println("No such padding - " + e);
return null;
} catch (IOException e) {
System.err.println("IO error - " + e);
return null;
}

}

public boolean decryptFile(String infile, String outfile, int keyType) {

try {

FileInputStream fstream = new FileInputStream(infile);

//read first 128 bytes for encrypted key
byte[] cKey = new byte[RSA_SIZE];
fstream.read(cKey);

// decrypt AES key with RSA
Cipher cs = Cipher.getInstance("RSA");
cs.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
byte[] raw = cs.doFinal(cKey);

SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.DECRYPT_MODE, skeySpec);


CipherInputStream cstream = new CipherInputStream(fstream, aesCipher);

FileOutputStream foutstream = new FileOutputStream(outfile);
byte[] b = new byte;
int i = cstream.read(b);
while (i != -1) {
foutstream.write(b, 0, i);
i = cstream.read(b);
}
return true;
} catch (FileNotFoundException e) {
System.err.println("File Not found - " + e);
return false;
} catch (InvalidKeyException e) {
System.err.println("Invalid key - " + e);
return false;
} catch (NoSuchAlgorithmException e) {
System.err.println("No such algorithm - " + e);
return false;
} catch (NoSuchPaddingException e) {
System.err.println("No such padding - " + e);
return false;
} catch (IOException e) {
System.err.println("IO error - " + e);
return false;
} catch (IllegalBlockSizeException e) {
System.err.println("Illegal block size - " + e);
return false;
} catch (BadPaddingException e) {
System.err.println("Bad padding exception - " + e);
return false;
}
}

public boolean decryptFileZip(String infile, String outfile, int keyType, String zipFile) {

try {
InputStream istream = null;
ZipFile zf = new ZipFile(zipFile);
ZipEntry ze = zf.getEntry(infile);
System.out.println("result of getEntry :" + ze);

if (ze != null) {

istream = zf.getInputStream(ze);

//read first 128 bytes for encrypted key
byte[] cKey = new byte[RSA_SIZE];
istream.read(cKey);

// decrypt AES key with RSA
Cipher cs = Cipher.getInstance("RSA");
cs.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
byte[] raw = cs.doFinal(cKey);

SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.DECRYPT_MODE, skeySpec);


CipherInputStream cstream = new CipherInputStream(istream, aesCipher);

FileOutputStream foutstream = new FileOutputStream(outfile);
byte[] b = new byte;
int i = cstream.read(b);
while (i != -1) {
foutstream.write(b, 0, i);
i = cstream.read(b);
}
foutstream.close();
zf.close();
istream.close();
return true;
}
else
return false;
} catch (FileNotFoundException e) {
System.err.println("File Not found - " + e);
return false;
} catch (InvalidKeyException e) {
System.err.println("Invalid key - " + e);
return false;
} catch (NoSuchAlgorithmException e) {
System.err.println("No such algorithm - " + e);
return false;
} catch (NoSuchPaddingException e) {
System.err.println("No such padding - " + e);
return false;
} catch (IOException e) {
System.err.println("IO error - " + e);
return false;
} catch (IllegalBlockSizeException e) {
System.err.println("Illegal block size - " + e);
return false;
} catch (BadPaddingException e) {
System.err.println("Bad padding exception - " + e);
return false;
}
}

/*public static void main (String[] args) {
EncryptUtil eu = new EncryptUtil("sysstore","store439");

eu.getKeys("syskey","cran1234");
System.out.println("Encrypting file");
eu.encryptFile("test.txt", "testenc.txt", EncryptUtil.PUBLIC_KEY);
System.out.println("Encrypted file");
System.out.println("Decrypting file");
eu.decryptFile("testenc.txt", "testres.txt", EncryptUtil.PRIVATE_KEY);
System.out.println("Decrypted file");
String ss = "Clear textl0asdfasdfaadsfadsfasdfgagggffasdfgggddfffffffffffffffffffffffffffffffffffffffffddddddddddddddddddddddddddddsdfasdfasdf";
System.out.println("Length of input " + ss.getBytes().length);
byte[] ctext = eu.encryptString(ss,EncryptUtil.PUBLIC_KEY);
System.out.println("Lenght of cipher " + ctext.length);
String rs = eu.decryptString(ctext,EncryptUtil.PRIVATE_KEY);
System.out.println(rs);
} */
}


-------------
HashFile.java
-------------
package com.ids;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.StringTokenizer;
import java.util.Iterator;
import java.util.Date;
import java.util.HashMap;
import java.util.ArrayList;
import java.security.cert.Certificate;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.KeyPair;
import java.security.Key;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.InvalidKeyException;
import java.security.cert.CertificateException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.BadPaddingException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;


/**
* @author John Lim
* Allows the creation and storage of file hashes in a database and
* to allow for checking of integrity by comparing hashes against
* the actual file in the file system. Also allows the identification of
* missing files in the file system.
*/

public class HashFile {

private String keyAlias;
private String keyPass;
private KeyStore keyStore;
private KeyPair keyPair;
private SecretKeySpec aesKSpec;
private BufferedReader bfstream;
private String hashFileName;
private HashMap monitoredFiles;
private Connection conn;

private String logID;
private Logger log;
private String quarantinePath;

private Cipher aesCipher;
private byte[] raw;
private configFile config;
public int RSA_SIZE = 2048;

public static final int FILE_HASH_MATCH = 0;
public static final int FILE_HASH_MISMATCH = 1;
public static final int FILE_HASH_NOT_EXIST = 2;
public static final int FILE_NOT_EXIST = 3;

public static final int PRIVATE_KEY = 1;
public static final int PUBLIC_KEY = 2;
final private String driverName = "com.mysql.jdbc.Driver";


/** Default constructor */
public HashFile() {
keyPair = null;
keyStore = null;
keyAlias = null;
keyPass = null;
aesKSpec = null;
quarantinePath = null;

logID = null;
log = null;
try {
Class.forName(driverName).newInstance();
} catch (Exception e) {
System.err.println("Cannot register jdbc driver : " + e);
}
try {
config = new configFile();
} catch(Exception e) {
System.err.println("Error loading properties file");
}

}

/**
* Constructor to open keystore, along with keystore password
* and hash file containing encrypted symmetric keys. If
* hash file does not exist, a new set of symmetric keys is
* created.
*/

public HashFile(String hashFile, String ks, String kp, String alias,
String keyPass) {
this();
hashFileName = hashFile;
monitoredFiles = new HashMap();


try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/+ids+?user=+idsuser+&password+=1d5u5er");
FileInputStream is = new FileInputStream(ks);
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(is, kp.toCharArray());
getKeys(alias,keyPass);
} catch (KeyStoreException e) {
System.err.println("Key store exception - " + e);
} catch (CertificateException e) {
System.err.println("Key store exception - " + e);
} catch (NoSuchAlgorithmException e) {
System.err.println("No such algorithm - " + e);
} catch (java.io.IOException e) {
System.err.println("IO exception - " + e);
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("VendorError: " + ex.getErrorCode());
}
try {
File hF = new File(hashFileName);
if (hF.exists() && hF.isFile() && (keyPair != null)) {

bfstream = new BufferedReader(new FileReader(hashFileName));

String encKey = bfstream.readLine();
//System.out.println("Length of encKey - " + encKey.length());

byte[] cKey = new BASE64Decoder().decodeBuffer(encKey);
//System.out.println("read bfstream - " + cKey.length);

// decrypt AES key with RSA
Cipher cs = Cipher.getInstance("RSA");
cs.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
raw = cs.doFinal(cKey);
//System.out.println("after dectypting with RSA" + raw.length);

aesKSpec = new SecretKeySpec(raw, "AES");
//System.out.println("after sss");
aesCipher = Cipher.getInstance("AES");
//System.out.println("after getinstance");
aesCipher.init(Cipher.DECRYPT_MODE, aesKSpec);
//System.out.println("after init");


bfstream.close();
}
else if (!hF.exists() && (keyPair != null)) {
// Need to delete all entries in database as the entries
// are no longer usable.
flushDb();

KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(256);


// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
raw = skey.getEncoded();

aesKSpec = new SecretKeySpec(raw, "AES");
aesCipher = aesCipher.getInstance("AES");

BufferedWriter bfstream = new BufferedWriter(new FileWriter(hashFileName,false));

Cipher cs = Cipher.getInstance("RSA");
cs.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
byte[] eRaw = cs.doFinal(raw);
//System.out.println("length encoded -" + eRaw.length);
String sRaw = Base64Converter.encode(eRaw);

bfstream.write(sRaw);
bfstream.newLine();

bfstream.close();
//aesCipher.init(Cipher.DECRYPT_MODE, aesKSpec);
}
} catch (InvalidKeyException e) {
System.err.println("Invalid key - " + e);
return;
} catch (NoSuchAlgorithmException e) {
System.err.println("No such algorithm - " + e);
return;
} catch (NoSuchPaddingException e) {
System.err.println("No such padding - " + e);
return;
} catch (IOException e) {
System.err.println("IO error - " + e);
return;
} catch (IllegalBlockSizeException e) {
System.err.println("Illegal block size - " + e);
return;
} catch (BadPaddingException e) {
System.err.println("Bad padding exception - " + e);
return;
}
}

public void setQuarantinePath (String path){
quarantinePath = path;
}
/**
* Returns an array of filenames which are missing
*/
public String[] getMissingFiles() {
ResultSet rs = null;
Statement stmt = null;
File file = null;
ArrayList fileList = new ArrayList();
String[] fileArr = null;;

try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT filepath FROM hash");

String filePath;
while (rs.next()) {
filePath = decrypt(rs.getString(1));
file = new File(filePath);
if (!file.exists()) {
fileList.add(filePath);
}
}
if (fileList.size() > 0) {
fileArr = new String[fileList.size()];
for (int i=0;i<fileList.size();i++)
fileArr[i] = (String)fileList.get(i);
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt = null;
}
}
return fileArr;

} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("VendorError: " + ex.getErrorCode());
return null;
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt = null;
}
}
}
}

/**
* Deletes ALL entries in the database
*/
public int flushDb () {
Statement stmt = null;
int rs;

try {
stmt = conn.createStatement();
rs = stmt.executeUpdate("DELETE FROM hash");
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt = null;
}
}
return rs;
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
return -1;
}
}

/**
* Compares the specified file's hash against that stored in the
* database. Returns :
* FILE_HASH_MATCH if both hashes match
* FILE_HASH_MISMATCH if both hashes mismatch
* FILE_HASH_NOT_EXIST if file does not have corresponding hash in db
* FILE_NOT_EXIST if file does not exist in the file system
*/
public int compareFileHash (String filePath) {

ResultSet rs = null;
Statement stmt = null;

try {
File file = new File(filePath);
String encFilePath = encrypt(file.getCanonicalPath());


stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT filehash FROM hash WHERE filepath='"+encFilePath+"'");

if (rs.next()) {
String fileHash = decrypt(rs.getString(1));

//System.out.println("obtained hash -" + fileHash);
String obtainedFileHash = HashUtil.hashFileEncoded(filePath);
//System.out.println("actual hash -" + obtainedFileHash);
if (fileHash.equals(obtainedFileHash)) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt = null;
}
}
return FILE_HASH_MATCH;
}
else {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt = null;
}
}
return FILE_HASH_MISMATCH;
}
}
else if (!file.exists()) {
System.err.println("File : " + filePath + " does not exist");
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt = null;
}
}
return FILE_NOT_EXIST;
}
else {
System.err.println("File : " + filePath + " is not in the hash file");
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt = null;
}
}
return FILE_HASH_NOT_EXIST;
}

} catch (IOException e) {
System.err.println("IO Exception - " + e);
return -1;
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("VendorError: " + ex.getErrorCode());
return -1;
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt = null;
}
}
}
}

/**
* Adds directory into the hash store. Parameter recursive should be
* true if all subdirectories are to be added. False otherwise.
*
* @param dirPath path of directory to be hashed
* @param recursive switch to include subdirectories
*/
public boolean addDirs (String dirPath, boolean recursive) {
try {


BufferedWriter bfstream = new BufferedWriter(new FileWriter(hashFileName,false));

Cipher cs = Cipher.getInstance("RSA");
cs.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
byte[] eRaw = cs.doFinal(raw);
//System.out.println("length encoded -" + eRaw.length);
String sRaw = Base64Converter.encode(eRaw);

bfstream.write(sRaw);
bfstream.newLine();
//System.out.println("Writing aes key - " + sRaw.length());

addDir (dirPath, recursive);
bfstream.close();
} catch (IOException e) {
System.err.println("Cannot open file for writing " + e);
return false;
} catch (NoSuchAlgorithmException e) {
System.err.println("No such algorithm - " + e);
return false;
} catch (InvalidKeyException e) {
System.err.println("Invalid key - " + e);
return false;
} catch (NoSuchPaddingException e) {
System.err.println("No such padding - " + e);
return false;
} catch (IllegalBlockSizeException e) {
System.err.println("Illegal block size - " + e);
return false;
} catch (BadPaddingException e) {
System.err.println("Bad padding exception - " + e);
return false;
}
return true;
}

public static void sortFileDir(File[] fileList) {
File temp;

for (int i=0;i<fileList.length;i++) {
for (int j=0;j<(fileList.length - i - 1);j++) {
if (fileList[j+1].isFile() && fileList[j].isDirectory()) {
temp = fileList[j];
fileList[j] = fileList[j+1];
fileList[j+1] = temp;
}
}
}
}

public static void sortFileDir(String path, String[] fileList) {
String temp;
File file1, file2;

for (int i=0;i<fileList.length;i++) {
for (int j=0;j<(fileList.length - i - 1);j++) {
file1 = new File(path+File.separatorChar+fileList[j]);
file2 = new File(path+File.separatorChar+fileList[j+1]);
if (file2.isFile() && file1.isDirectory()) {
temp = fileList[j];
fileList[j] = fileList[j+1];
fileList[j+1] = temp;
}
}
}
}

public void quarantine(String file) {
File fObj = new File(file);
File tgt = new File(quarantinePath + File.separatorChar +
file.substring(file.lastIndexOf(File.separatorChar)+1,file.length()));
fObj.renameTo(tgt);
fObj = new File(file);
fObj.delete();
}
private boolean addDir (String dirPath, boolean recursive) {
File fileDirPath = new File(dirPath);
try {
if (fileDirPath.isDirectory()) {
File[] fileList = fileDirPath.listFiles();
for (int i=0;i<fileList.length;i++) {
if (fileList[i].isFile()) {
addFileHash(fileList[i]);
}
else if (fileList[i].isDirectory()) {
if (recursive) {
addDir(fileList[i].getCanonicalPath(),true);
}
}
}
}
} catch (IOException e) {
System.err.println("File error " + e);
return false;
}
return true;
}


private String encrypt(String inLine) {
try {
Cipher aesEncryptCipher = Cipher.getInstance("AES");
aesEncryptCipher.init(Cipher.ENCRYPT_MODE, aesKSpec);

byte[] outByte = aesEncryptCipher.doFinal(inLine.getBytes());
String out = Base64Converter.encode(outByte);
return out;
} catch (NoSuchAlgorithmException e) {
System.err.println("No such algorithm - " + e);
return null;
} catch (InvalidKeyException e) {
System.err.println("Invalid key - " + e);
return null;
} catch (IllegalBlockSizeException e) {
System.err.println("Illegal block size - " + e);
return null;
} catch (NoSuchPaddingException e) {
System.err.println("No such padding - " + e);
return null;
} catch (BadPaddingException e) {
System.err.println("Bad padding exception - " + e);
return null;
}
}

private void addFileHash(File f) throws IOException {
Statement stmt = null;

int res;
try {

String fileHash = HashUtil.hashFileEncoded(f.getCanonicalPath());
stmt = conn.createStatement();
res = stmt.executeUpdate("INSERT INTO hash (filepath, filehash, filedate) "+
"VALUES ('"+ encrypt(f.getCanonicalPath())+"','"+encrypt(fileHash)+
"','"+encrypt((new Date(f.lastModified())).toString())+"')");
//System.out.println(stmt);
String outStr = f.getCanonicalPath() + "|" +
fileHash + "|" +
(new Date(f.lastModified())).toString();


if (log != null) {
log.log(Level.INFO,"Updating hash:"+outStr);
}
else {
//System.out.println("Updating hash:"+outStr);
}


} catch (SQLException ex) {
// handle any errors
System.err.println("SQLException: " + ex.getMessage());
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("VendorError: " + ex.getErrorCode());
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt = null;
}
}
}
}



private String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new BASE64Decoder().decodeBuffer(str);

// Decrypt
byte[] utf8 = aesCipher.doFinal(dec);

// Decode using utf-8
return new String(utf8);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}

// Retrieves keys associated to alias and associated password
private void getKeys(String alias, String pass) {
keyAlias = alias;
keyPass = pass;
keyPair = getKey();
}

private KeyPair getKey() {
try {
// Get private key
Key key = keyStore.getKey(keyAlias, keyPass.toCharArray());
if (key instanceof PrivateKey) {
// Get certificate of public key
java.security.cert.Certificate cert = keyStore.getCertificate(keyAlias);

// Get public key
PublicKey publicKey = cert.getPublicKey();

// Return a key pair
return new KeyPair(publicKey, (PrivateKey)key);
}
} catch (UnrecoverableKeyException e) {
System.err.println("Key exception - " + e);
} catch (NoSuchAlgorithmException e) {
System.err.println("No such algorithm - " + e);
} catch (KeyStoreException e) {
System.err.println("Key store exception - " + e);
}
return null;
}

/**
* Sets the log object for logging
*/
public void setLogger (String logString) {
logID = logString;
log = Logger.getLogger(logID);
log.setUseParentHandlers(false);
return;
}

/*public static void main(String[] args) {
//HashFile hf = new HashFile("/usr/ids/hash.lst", "sysstore","store439", "syskey", "cran1234");
HashFile hf = new HashFile();
//hf.addDirs("I:\\IDS Project", true);
//System.out.println(hf.flushDb());
//System.out.println(hf.compareFileHash("I:"+File.separatorChar+"IDS project"+
// File.separatorChar+"configFile.java"));
//String[] arr = hf.getMissingFiles();
//for (int i=0;i<arr.length;i++)
// System.out.println(arr[i]);

hf.setQuarantinePath("/usr/ids/com/ids/quarantine");
hf.quarantine("/usr/ids/com/ids/test.txt");
} */
}


-------------
HashUtil.java
-------------
package com.ids;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.DigestException;
import java.security.DigestInputStream;
import java.security.NoSuchAlgorithmException;
import sun.misc.BASE64Encoder;


public class HashUtil {

public static byte[] hashFile (String filename) {
File file = new File (filename);
try {
if (file.exists()) {
FileInputStream fstream = new FileInputStream(file);
MessageDigest md = MessageDigest.getInstance("SHA-256");
DigestInputStream dStream = new DigestInputStream(fstream,md);


int res = dStream.read();

do {
res = dStream.read();
} while (res>=0);

byte[] fileDigest = md.digest();

return fileDigest;
}
else
return null;
} catch (FileNotFoundException e) {
return null;
} catch (NoSuchAlgorithmException e) {
return null;
} catch (IOException e) {
return null;
}

}


public static String hashFileEncoded (String filename) {
File file = new File (filename);
try {
if (file.exists() && (file.isFile())) {
FileInputStream fstream = new FileInputStream(file);
MessageDigest md = MessageDigest.getInstance("SHA-512");
DigestInputStream dStream = new DigestInputStream(fstream,md);


int res = dStream.read();

do {
res = dStream.read();
} while (res>=0);

byte[] fileDigest = md.digest();

String s = new BASE64Encoder().encode(fileDigest);
return s;

}
else
return null;
} catch (FileNotFoundException e) {
return null;
} catch (NoSuchAlgorithmException e) {
return null;
} catch (IOException e) {
return null;
}

}
/*public static void main(String[] args) {
byte[] abc = HashUtil.hashFile("Specifications.doc");
String s = new BASE64Encoder().encode(abc);
System.out.println(s);
}*/
}

--------
IDS.java
--------
package com.ids;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import java.io.*;
import java.util.logging.*;
import java.util.*;
import com.ids.*;

public class IDS extends Thread {

private static mList list;
private static int agentCnt;
private static Agency thread;
private configFile config;
private SecureBackup sb;
private SecuredServer ss;
private Logger lg;

public IDS() {
//menuBar = new JMenuBar( );
try {
config = new configFile();
lg = Logger.getLogger(config.getlogName());
FileHandler fh = new FileHandler(config.getlogFilename(),true);
lg.addHandler(fh);
agentCnt = Integer.parseInt(config.getthreadCnt());
} catch (IOException e) {
System.err.println("Error creating log file : " + config.getlogFilename());
} catch(Exception e) {
System.err.println("Error loading properties file : " + e);
return;
}
}

public void run(){
File f = new File("hash.lst");
if (!f.exists()) {
baseLine();
lg.log(Level.INFO,"Running baseline");
}
thread = new Agency();
thread.setLogger(config.getlogName());
thread.start();
ss = new SecuredServer();
ss.setLogger(config.getlogName());
ss.setThread(thread);
ss.start();
/*while (thread.isAlive()) {
try {
long numMillisecondsToSleep = 30000; // 5 seconds
Thread.sleep(numMillisecondsToSleep);
} catch (InterruptedException e) {
}
}*/

}

public void stopApp() {
thread.terminate = true;
this.interrupt();
}

public void baseLine() {
//System.out.println ("Please wait ...");
HashFile hf = new HashFile("hash.lst", "sysstore","store439", "syskey", "cran1234");
hf.setLogger(config.getlogName());
int cnt = 0;
boolean flag;
while (cnt < 5 && config.getbackupLoc(cnt) != null) {
if (config.getbackupRecurFlag(cnt).equals("true"))
flag = true;
else
flag = false;
hf.addDirs(config.getbackupLoc(cnt), flag);

if (cnt<1)
sb = new SecureBackup(config.getbackupLoc(cnt), Boolean.getBoolean(config.getbackupRecurFlag(cnt)), config.getBKLOC(),true);
else
sb.addBackupDir(config.getbackupLoc(cnt));

cnt++;
}
if (cnt>0)
sb.createBackup();

}

}


-----------------
SecureBackup.java
-----------------
package com.ids;

import java.util.*;
import java.io.*;
import java.util.zip.*;


public class SecureBackup {
private String location;
private String bkLoc;
private ArrayList tgtLoc;

private ArrayList secureFileList, actualFileList;
private boolean bothDir;
private boolean zip;


public SecureBackup() {
secureFileList = new ArrayList();
actualFileList = new ArrayList();
tgtLoc = new ArrayList();
bothDir = false;
zip = false;
}

public SecureBackup(String tgtLocation, String bkLocation) {
// read file info from backup location
this();
bkLoc = bkLocation;
tgtLoc.add(new TgtLocObject(tgtLocation, true));
File tgtLocF = new File(tgtLocation);
File bkLocF = new File(bkLoc);
if (tgtLocF.isDirectory() && bkLocF.isDirectory())
bothDir = true;
// initalize location to actual location

}

public SecureBackup(String tgtLocation, boolean rec, String bkLocation) {
// read file info from backup location
this();
bkLoc = bkLocation;
tgtLoc.add(new TgtLocObject(tgtLocation, rec));
File tgtLocF = new File(tgtLocation);
File bkLocF = new File(bkLoc);
if (tgtLocF.isDirectory() && bkLocF.isDirectory())
bothDir = true;
// initalize location to actual location

}

public SecureBackup(String tgtLocation, String bkLocation, boolean zipYes) {
// read file info from backup location
this();
bkLoc = bkLocation;
tgtLoc.add(new TgtLocObject(tgtLocation, true));
File tgtLocF = new File(tgtLocation);
File bkLocF = new File(bkLoc);
if (!zipYes) {
if (tgtLocF.isDirectory() && bkLocF.isDirectory())
bothDir = true;
}
else {
if (tgtLocF.isFile() && bkLocF.isDirectory())
bothDir = true;
}
zip = zipYes;
// initalize location to actual location

}

public SecureBackup(String tgtLocation, boolean rec,
String bkLocation, boolean zipYes) {
// read file info from backup location
this();
bkLoc = bkLocation;
tgtLoc.add(new TgtLocObject(tgtLocation, rec));
File tgtLocF = new File(tgtLocation);
File bkLocF = new File(bkLoc);
if (!zipYes) {
if (tgtLocF.isDirectory() && bkLocF.isDirectory())
bothDir = true;
}
else {
if (tgtLocF.isFile() && bkLocF.isDirectory())
bothDir = true;
}
zip = zipYes;
// initalize location to actual location

}
public void addBackupDir(String tgtLocation) {
tgtLoc.add(new TgtLocObject(tgtLocation, true));
}

public void addBackupDir(String tgtLocation, boolean rec) {
tgtLoc.add(new TgtLocObject(tgtLocation, rec));
}

public boolean createBackup() {
File tgtLocF;
ZipFile zipF;

ArrayList dirList = new ArrayList();

for (int j=0;j<tgtLoc.size();j++) {
tgtLocF = new File(((TgtLocObject)tgtLoc.get(j)).getLocation());
//System.out.println(((TgtLocObject)tgtLoc.get(j)).getLocation());
File[] fList = tgtLocF.listFiles();
if (fList != null)
fillList(fList, actualFileList, dirList,
((TgtLocObject)tgtLoc.get(j)).getRecursive());
else
continue;

if (zip) {
EncryptUtil eu = new EncryptUtil("sysstore","store439");
eu.getKeys("syskey","cran1234");

eu.encryptFileZip(actualFileList,bkLoc,
EncryptUtil.PUBLIC_KEY);

}
else {
File bkLocF = new File(bkLoc + File.separatorChar +
String.valueOf(j));
if (!bkLocF.exists())
bkLocF.mkdir();
if (bothDir && dirIsEmpty(bkLocF)) {
EncryptUtil eu = new EncryptUtil("sysstore","store439");
eu.getKeys("syskey","cran1234");

//create directories first
for (int i=0;i<dirList.size();i++) {
String dirString = (String)dirList.get(i);
File dir = new File(bkLocF.getAbsolutePath() +
dirString.substring(tgtLocF.getAbsolutePath().length()));
//System.out.println("creating dir " + (String)dirList.get(i) +
// " " + dir.mkdir());
}

//create encrypted files
for (int i=0;i<actualFileList.size();i++) {
//create backup files
String absFileName = (String)actualFileList.get(i);
String fileName = absFileName.substring(tgtLocF.getAbsolutePath().length());
String tgtfileName = bkLocF.getAbsolutePath() + fileName;
//System.out.println("Encrypting to " + tgtfileName);
eu.encryptFile(absFileName,tgtfileName,
EncryptUtil.PUBLIC_KEY);
}
}
}
}
return true;
}

private boolean dirIsEmpty(File dir) {
if (dir.isDirectory()) {
if (dir.listFiles().length == 0)
return true;
else
return false;
}
else
return false;
}

private void fillList(File[] files, ArrayList list, ArrayList dirList,
boolean recursive) {
String absPath;
for (int i=0;i<files.length;i++) {
if (files[i].isFile()) {
absPath = files[i].getAbsolutePath();
//System.out.println("adding " + absPath);
list.add(absPath);
}
else if (recursive){
File[] fList = files[i].listFiles();
dirList.add(files[i].getAbsolutePath());
//System.out.println("adding dir " + files[i].getAbsolutePath());
fillList(fList, list, dirList, recursive);
}
}
}
// gives true or false depending on matching files
// from both location and backup location
public boolean sync() {
return true;
}

// restores the file specified in the original location
public boolean restore (String file) {
String prefix;
File tgtLocF = null;
int index = -1;


//System.out.println(bkLoc);
if (zip) {
EncryptUtil eu = new EncryptUtil("sysstore","store439");
eu.getKeys("syskey","cran1234");
eu.decryptFileZip(file, file,
EncryptUtil.PRIVATE_KEY, bkLoc);
return true;
}
else {
//look for the backup directories matching file
for (int i=0;i<tgtLoc.size();i++) {
tgtLocF = new File(((TgtLocObject)tgtLoc.get(i)).getLocation());
if (tgtLocF.getAbsolutePath().length() < file.length()) {
prefix = file.substring(0,tgtLocF.getAbsolutePath().length());
if (prefix.equals(((TgtLocObject)tgtLoc.get(i)).getLocation())) {
index = i;
break;
}
}
}


File bkLocF = new File(bkLoc);
File bkFile = new File(bkLocF.getAbsolutePath() + File.separatorChar +
String.valueOf(index) + File.separatorChar +
file.substring(tgtLocF.getAbsolutePath().length()+1));
//System.out.println(bkLocF.getAbsolutePath() + File.separatorChar +
// String.valueOf(index) + File.separatorChar +
// file.substring(tgtLocF.getAbsolutePath().length()+1));
if (bkFile.exists()) {
EncryptUtil eu = new EncryptUtil("sysstore","store439");
eu.getKeys("syskey","cran1234");
eu.decryptFile(bkFile.getAbsolutePath(), file,
EncryptUtil.PRIVATE_KEY);
return true;
}

return false;
}
}

public boolean restore (String file, String newName) {
String prefix;
File tgtLocF = null;
int index = -1;

//look for the backup directories matching file


if (zip) {
EncryptUtil eu = new EncryptUtil("sysstore","store439");
eu.getKeys("syskey","cran1234");
eu.decryptFileZip(file, newName,
EncryptUtil.PRIVATE_KEY, bkLoc);
return true;
}
else {
for (int i=0;i<tgtLoc.size();i++) {
tgtLocF = new File(((TgtLocObject)tgtLoc.get(i)).getLocation());
if (tgtLocF.getAbsolutePath().length() < file.length()) {
prefix = file.substring(0,tgtLocF.getAbsolutePath().length());
//System.out.println(prefix);
//System.out.println((String)tgtLoc.get(i));
if (prefix.equals(((TgtLocObject)tgtLoc.get(i)).getLocation())) {
index = i;
break;
}
}
}


File bkLocF = new File(bkLoc);
File bkFile = new File(bkLocF.getAbsolutePath() +File.separatorChar+
String.valueOf(index) + File.separatorChar +
file.substring(tgtLocF.getAbsolutePath().length()));
if (bkFile.exists()) {
EncryptUtil eu = new EncryptUtil("sysstore","store439");
eu.getKeys("syskey","cran1234");
eu.decryptFile(bkFile.getAbsolutePath(), newName,
EncryptUtil.PRIVATE_KEY);
return true;
}

return false;
}
}

/*public static void main(String[] args) {
SecureBackup sb = new SecureBackup("G:\\IDS Project",false,"G:\\idsbk\\bk.zip",true);
sb.addBackupDir("G:\\fypj",true);
sb.createBackup();
//sb.restore("G:\\IDS Project\\CreateKeys.bat","G:\\IDS Project\\CreateKeys3.bat");
}*/

}


------------------
SecuredClient.java
------------------

/*
* SecuredClient.java
*
* Created on November 25, 2004, 4:10 PM
*/

package com.ids;

import java.io.*;
import javax.net.ssl.*;
import java.security.*;

/**
*
* @author root
*/
public class SecuredClient {
private int port = 1913;
private String host = "localhost";
private SSLSocket sSocket;

private static final String STOP = "A01";
private static final String START = "A02";
private static final String ACTIVE = "A03";
private static final String INACTIVE = "A04";
private static final String STATUS = "A05";

/** Creates a new instance of SecuredClient */
public SecuredClient() {


/*
* Set up a key manager for client authentication
* if asked by the server. Use the implementation's
* default TrustStore and secureRandom routines.
*/
SSLSocketFactory factory = null;
try {
SSLContext ctx;
KeyManagerFactory kmf;
KeyStore ks;
char[] passphrase = "store439".toCharArray();
char[] keyphrase = "cran1234".toCharArray();

ctx = SSLContext.getInstance("SSL");
kmf = KeyManagerFactory.getInstance("SunX509");
ks = KeyStore.getInstance("JKS");

ks.load(new FileInputStream("clientstore"), passphrase);

kmf.init(ks, keyphrase);
TrustManagerFactory trustFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustFactory.init(ks);
TrustManager[] trustManagers = trustFactory.getTrustManagers();

ctx.init(kmf.getKeyManagers(), trustManagers, null);

factory = ctx.getSocketFactory();
} catch (Exception e) {
System.err.println("Exception - " + e);
}
try {
sSocket = (SSLSocket)factory.createSocket(host, port);
} catch (IOException e) {
System.err.println("IOException - " + e);
}
}

public void startService() {
sendMsg(START);
}

public void stopService() {
sendMsg(STOP);
}

public int status () {
try {
DataOutputStream out =
new DataOutputStream(sSocket.getOutputStream());
DataInputStream in =
new DataInputStream(sSocket.getInputStream());
out.writeUTF(STATUS);
out.flush();
byte[] buf = new byte[20];
int bufSize = in.read(buf);

String st = new String(buf, 0, bufSize);
in.close();
out.close();
sSocket.close();
if (st.equals(ACTIVE))
return 1;
else if (st.equals(INACTIVE))
return 0;
else return -1;
} catch (IOException e) {
System.err.println("error - " + e);
}
return -1;
}

private void sendMsg(String s) {
try {
DataOutputStream out =
new DataOutputStream(sSocket.getOutputStream());

out.writeUTF(s);
out.flush();
out.close();
} catch (IOException e) {
System.err.println("error - " + e);
}
}

public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
SecuredClient s = new SecuredClient();
//System.setProperty("javax.net.ssl.keyStore","truststore");
//System.setProperty("javax.net.ssl.keyStorePassword","store439");
System.out.println("Enter 1 for status");
System.out.println("Enter 2 for start");
System.out.println("Enter 3 for stop");
String input = in.readLine();
if (input.equals("2"))
s.startService();
else if (input.equals("3"))
s.stopService();
else if (input.equals("1")) {
System.out.println(s.status());
}
//SecuredClient s = new SecuredClient();
//s.sendMsg("Hello");
}

}


-------------------
SecuredServer.java
-------------------

/*
* SecuredServer.java
*
* Created on November 25, 2004, 3:44 PM
*/

package com.ids;

import java.io.*;
import java.util.logging.*;
import java.util.*;
import java.net.*;
import javax.net.ssl.*;
import javax.net.*;
import java.security.*;
import java.security.cert.*;
/**
*
* @author John Lim
*
*/
public class SecuredServer extends Thread{

private final int port = 1913;
private SSLServerSocket sSock;
private Socket sSocket;
private Agency thread;

private configFile config;

private ArrayList actionList;
private boolean stop = false;
private Logger log;

private static final String STOP = "A01";
private static final String START = "A02";
private static final String ACTIVE = "A03";
private static final String INACTIVE = "A04";
private static final String STATUS = "A05";
private static final String BASELINE = "A06";

/** Creates a new instance of SecuredServer */
public SecuredServer() {


try {
actionList = new ArrayList();
SSLContext ctx;
KeyManagerFactory kmf;
KeyStore ks;
config = new configFile();
char[] passphrase = "store439".toCharArray();
char[] keypass = "cran1234".toCharArray();

ctx = SSLContext.getInstance("SSL");
kmf = KeyManagerFactory.getInstance("SunX509");
ks = KeyStore.getInstance("JKS");

ks.load(new FileInputStream("sysstore"), passphrase);
kmf.init(ks, keypass);

TrustManagerFactory trustFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustFactory.init(ks);
TrustManager[] trustManagers = trustFactory.getTrustManagers();

ctx.init(kmf.getKeyManagers(), trustManagers, null);

SSLServerSocketFactory SrvFact =
ctx.getServerSocketFactory();

sSock = (SSLServerSocket)SrvFact.createServerSocket(port);
sSock.setNeedClientAuth(true);

} catch (IOException e) {
System.err.println("Error creating socket - "+ e);
} catch (NoSuchAlgorithmException ex) {
System.err.println("Algorithm error - " + ex);
} catch (KeyStoreException e) {
System.err.println("KeyStoreException - " + e);
} catch (CertificateException e) {
System.err.println("KeyStoreException - " + e);
} catch (UnrecoverableKeyException e) {
System.err.println("KeyStoreException - " + e);
} catch (KeyManagementException e) {
System.err.println("KeyStoreException - " + e);
}
}

public void setThread (Thread tr) {
thread = (Agency)tr;
}

public void listen() {
try {
System.out.println("listening on " + port);
sSocket = sSock.accept();
InetAddress inetadd = sSocket.getInetAddress();
String host = inetadd.getHostAddress();
ArrayList hostAllowed = config.getAllowedHosts();
boolean found = false;
for (int i=0;i<hostAllowed.size();i++) {
if (((String)hostAllowed.get(i)).equals(host))
found = true;
}
if (!found) {
System.err.println("Illegal host attempt to connect - " + host);
return;
}
SecuredServerAction ssa = new SecuredServerAction();
ssa.setThread(thread);
ssa.setSocket(sSocket);
ssa.setLogger(log);
ssa.run();
actionList.add(ssa);

return;
} catch (SSLHandshakeException e) {
System.err.println("Certficate error - " + e);
}
catch (IOException e) {
System.err.println("IO Error - " + e);
}
return;
}

public void interrupt() {
stop = true;
}



public void run () {
String msg;
log.log(Level.INFO,"Started Secured Server");
while (true) {
listen();
}


}

public void setLogger (String logString) {
log = Logger.getLogger(logString);
log.setUseParentHandlers(false);
return;
}
}

------------------------
SecuredServerAction.java
------------------------

/*
* SecuredServerAction.java
*
* Created on December 2, 2004, 5:03 PM
*/

package com.ids;
import java.net.*;
import javax.net.ssl.*;
import javax.net.*;
import java.util.*;
import java.io.*;
import java.util.logging.*;
/**
*
* @author root
*/
public class SecuredServerAction extends Thread{

private Agency thread;
private DataOutputStream out;
private DataInputStream in;
private Socket sSocket;
private Logger log;
private configFile config;

private static final String STOP = "A01";
private static final String START = "A02";
private static final String ACTIVE = "A03";
private static final String INACTIVE = "A04";
private static final String STATUS = "A05";
private static final String BASELINE = "A06";

/** Creates a new instance of SecuredServerAction */
public SecuredServerAction() {
}

public void run() {
try {
in = new DataInputStream(sSocket.getInputStream());
out = new DataOutputStream(sSocket.getOutputStream());
while (!sSocket.isClosed()) {
String msg = in.readUTF();
if (!(msg == null) && (msg.equals(STOP))) {
thread.stopMonitor();
System.err.println("Stopped Service");
log.log(Level.INFO,"Stopped Service");
}
else if (!(msg == null) && (msg.equals(START))) {
thread.startMonitor();
System.err.println("Started Service");
log.log(Level.INFO,"Started Service");
}
else if (!(msg == null) && (msg.equals(STATUS))) {
try {
int stat = thread.status();
if (stat == 0)
out.write(INACTIVE.getBytes());
else
out.write(ACTIVE.getBytes());
out.flush();
} catch (IOException e) {
System.err.println("Socket write error - " + e);
}
}
else if (!(msg == null) && (msg.equals(BASELINE))) {
boolean active = false;
if (thread.status() == 1) {
active = true;
thread.stopMonitor();
log.log(Level.INFO,"Stopped Service");
}
baseLine();
log.log(Level.INFO,"BaseLined files");
if (active) {
thread.startMonitor();
log.log(Level.INFO,"Started Service");
}

}
}
} catch (IOException e) {
log.log(Level.INFO, "IDS Console " + sSocket.getInetAddress().toString() +
" has logged off");
//System.err.println("IO Error - " + e);
}
}

public void baseLine() {
//System.out.println ("Please wait ...");
try {
HashFile hf = new HashFile("hash.lst", "sysstore","store439", "syskey", "cran1234");
SecureBackup sb = null;

config = new configFile();
hf.flushDb();
hf.setLogger(config.getlogName());
int cnt = 0;
boolean flag;
while (cnt < 5 && config.getbackupLoc(cnt) != null) {
if (config.getbackupRecurFlag(cnt).equals("true"))
flag = true;
else
flag = false;
hf.addDirs(config.getbackupLoc(cnt), flag);

if (cnt<1)
sb = new SecureBackup(config.getbackupLoc(cnt), Boolean.getBoolean(config.getbackupRecurFlag(cnt)), config.getBKLOC(),true);
else
sb.addBackupDir(config.getbackupLoc(cnt));

cnt++;
}
if (cnt>0)
sb.createBackup();
} catch (IOException e) {
System.err.println("Cannot open config file - " + e);
}

}
public void setThread (Thread tr) {
thread = (Agency)tr;
}

public void setSocket (Socket s) {
sSocket = s;
}

public void setLogger (Logger l) {
log = l;
}
}


------------
SendSMS.java
------------
package com.ids;

import java.sql.*;
import java.io.*;
import java.net.*;



public class SendSMS {

final String driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
String serverName, portNumber;
String databaseName, uName, uPwd;

public SendSMS (String sN, String dN, String uN, String uP) {
serverName = sN;
portNumber = "1433"; //default port for MSSql2000
databaseName = dN;
uName = uN;
uPwd = uP;
}

public SendSMS (String sN, String pN, String dN, String uN, String uP) {
serverName = sN;
portNumber = pN;
databaseName = dN;
uName = uN;
uPwd = uP;
}

public boolean sendMsg (String target, String msg) {
try {
Date sendDate = new Date((new java.util.Date()).getTime());
Class.forName(driverName);
String connString = "jdbc:microsoft:sqlserver://" + serverName + ":" + portNumber + ";";
connString += "User=" + uName + ";Password=" + uPwd + ";DatabaseName=" + databaseName;

Connection connection = DriverManager.getConnection (connString);
Statement stmt = connection.createStatement();
String sql = "INSERT INTO OutQueue (DateRecorded, DateOut, Recipient, Message, MsgOwner, Status) " +
"VALUES('" +sendDate.toString()+"','"+sendDate.toString()+"','"+target+"','" +
msg+"','CONSOLE', 'U')";
stmt.executeUpdate(sql);
connection.close();
return true;
} catch (ClassNotFoundException e) {
System.err.println("Cannot find class" + e);
return false;
// Could not find the database driver
} catch (SQLException e) {
System.err.println("SQL Exception" + e);
return false;
// Could not connect to the database
}
}


public static String sendSMSCNC (String target, String msg) {
BufferedReader in = null;

URL u;
String returnString;

try {
String newMsg = msg.replace(' ', '+');
String tmp = "http://cncsms.nyp.edu.sg/servlet/commz.servlet.SendMsg?";
tmp = tmp + "id=wwwalert&n=" + target + "&msg=" + newMsg;
tmp = tmp + "&desc=IDS+Server";
u = new URL(tmp);

URLConnection urlConn = u.openConnection();
urlConn.setDoOutput(true);

in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

int i=0;
String str;
String returnCode = "";
while ((str = in.readLine()) != null)
{
returnCode += str;
if (i > 20000)
break;
i++;
}

in.close();

return returnCode;
} catch (Exception e) {
System.err.println("Error sending sms - " + e);
}
return null;

}
/*public static void main(String[] args) {

SendSMS sms = new SendSMS("172.20.134.252","SMS","hack","hack");
System.out.println(sms.sendMsg("91522608","Hello I am here"));
}*/

}


----------------
ServiceMain.java
----------------
package com.ids;

import org.tanukisoftware.wrapper.WrapperManager;
import org.tanukisoftware.wrapper.WrapperListener;

public class ServiceMain
implements WrapperListener
{
private IDS idsApp;

/*---------------------------------------------------------------
* Constructors
*-------------------------------------------------------------*/
private ServiceMain()
{
}

/*---------------------------------------------------------------
* WrapperListener Methods
*-------------------------------------------------------------*/
/**
* The start method is called when the WrapperManager is signaled by the
* native wrapper code that it can start its application. This
* method call is expected to return, so a new thread should be launched
* if necessary.
*
* @param args List of arguments used to initialize the application.
*
* @return Any error code if the application should exit on completion
* of the start method. If there were no problems then this
* method should return null.
*/
public Integer start( String[] args )
{
idsApp = new IDS();
idsApp.start();

return null;
}

/**
* Called when the application is shutting down. The Wrapper assumes that
* this method will return fairly quickly. If the shutdown code code
* could potentially take a long time, then WrapperManager.signalStopping()
* should be called to extend the timeout period. If for some reason,
* the stop method can not return, then it must call
* WrapperManager.stopped() to avoid warning messages from the Wrapper.
*
* @param exitCode The suggested exit code that will be returned to the OS
* when the JVM exits.
*
* @return The exit code to actually return to the OS. In most cases, this
* should just be the value of exitCode, however the user code has
* the option of changing the exit code if there are any problems
* during shutdown.
*/
public int stop( int exitCode )
{
idsApp.stopApp();

return exitCode;
}

/**
* Called whenever the native wrapper code traps a system control signal
* against the Java process. It is up to the callback to take any actions
* necessary. Possible values are: WrapperManager.WRAPPER_CTRL_C_EVENT,
* WRAPPER_CTRL_CLOSE_EVENT, WRAPPER_CTRL_LOGOFF_EVENT, or
* WRAPPER_CTRL_SHUTDOWN_EVENT
*
* @param event The system control signal.
*/
public void controlEvent( int event )
{
if (WrapperManager.isControlledByNativeWrapper()) {
// The Wrapper will take care of this event
} else {
// We are not being controlled by the Wrapper, so
// handle the event ourselves.
if ((event == WrapperManager.WRAPPER_CTRL_C_EVENT) ||
(event == WrapperManager.WRAPPER_CTRL_CLOSE_EVENT) ||
(event == WrapperManager.WRAPPER_CTRL_SHUTDOWN_EVENT)){
WrapperManager.stop(0);
}
}
}

/*---------------------------------------------------------------
* Main Method
*-------------------------------------------------------------*/
public static void main( String[] args )
{
// Start the application. If the JVM was launched from the native
// Wrapper then the application will wait for the native Wrapper to
// call the application's start method. Otherwise the start method
// will be called immediately.
WrapperManager.start( new ServiceMain(), args );
}
}

-----------------
TgtLocObject.java
-----------------
package com.ids;

public class TgtLocObject {
private String tgtLoc;
private boolean recursive;

public TgtLocObject() {
tgtLoc = null;
recursive = false;
}
public TgtLocObject(String loc, boolean rec) {
tgtLoc = loc;
recursive = rec;
}

public void setLocation(String loc) {
tgtLoc = loc;
}

public void setRecursive(boolean rec) {
recursive = rec;
}

public String getLocation() {
return tgtLoc;
}

public boolean getRecursive() {
return recursive;
}
}


---------------
configFile.java
---------------

package com.ids;

import java.io.*;
import java.util.*;

public class configFile {
private static String BKLOC;
private static String qPath;
private static String excludedfx;
private static String checkInt;
private static String cycleInt;
private static String threadCnt;
private static String keyStore;
private static String smsServer;
private static String smsDB;
private static String smsDBid;
private static String smsDBpw;
private static String logFilename;
private static String logName;
private static String logErrname;
private static String message[] = new String[4];
private static ArrayList backupLoc = new ArrayList();
private static ArrayList backupRecurFlag = new ArrayList();
private static ArrayList sms = new ArrayList();
private static ArrayList allowedHost = new ArrayList();
private static boolean loaded = false;
private static final int backupCount = 5;

public configFile() throws IOException {
if (!loaded) {
loadProperties();
loaded = true;
}
}

public String getBKLOC() {
return BKLOC;
}

public String getqPath() {
return qPath;
}

public String getexcludedfx() {
return excludedfx;
}

public String getcheckInt() {
return checkInt;
}

public String getcycleInt() {
return cycleInt;
}

public String getthreadCnt() {
return threadCnt;
}

public String getkeyStore() {
return keyStore;
}

public String getsmsServer() {
return smsServer;
}

public String getsmsDB() {
return smsDB;
}

public String getsmsDBid() {
return smsDBid;
}

public String getsmsDBpw() {
return smsDBpw;
}

public String getlogFilename() {
return logFilename;
}

public String getlogName() {
return logName;
}

public String getlogErrname() {
return logErrname;
}

public String getMessage(int cnt) {
return message[cnt];
}

public String getbackupLoc(int cnt) {
if (cnt<backupLoc.size())
return (String)backupLoc.get(cnt);
else
return null;
}

public String getbackupRecurFlag(int cnt) {
if (cnt<backupRecurFlag.size())
return (String)backupRecurFlag.get(cnt);
else
return null;
}

public String getsms(int cnt) {
if (cnt<sms.size())
return (String)sms.get(cnt);
else
return null;
}

public synchronized ArrayList getAllowedHosts() {
return allowedHost;
}

public synchronized void setBKLOC(String newBKLOC) {
BKLOC = newBKLOC;
}

public synchronized void setqPath(String newqPath) {
qPath = newqPath;
}

public synchronized void setexcludedfx(String newexcludedfx) {
excludedfx = newexcludedfx;
}

public synchronized void setcheckInt(String newcheckInt) {
checkInt = newcheckInt;
}

public synchronized void setcycleInt(String newcycleInt) {
cycleInt = newcycleInt;
}

public synchronized void setthreadCnt(String newthreadCnt) {
threadCnt = newthreadCnt;
}

public synchronized void setkeyStore(String newkeyStore) {
keyStore = newkeyStore;
}

public synchronized void setsmsServer(String newsmsServer) {
smsServer = newsmsServer;
}

public synchronized void setsmsDB(String newsmsDB) {
smsDB = newsmsDB;
}

public synchronized void setsmsDBid(String newsmsDBid) {
smsDBid = newsmsDBid;
}

public synchronized void setsmsDBpw(String newsmsDBpw) {
smsDBpw = newsmsDBpw;
}

public synchronized void setlogFilename(String newlogFilename) {
logFilename = newlogFilename;
}

public synchronized void setlogName(String newlogName) {
logName = newlogName;
}

public synchronized void setlogErrname(String newlogErrname) {
logErrname = newlogErrname;
}

public synchronized void setMessage(int cnt, String newMessage) {
message[cnt] = newMessage;
}

public void loadProperties() throws IOException {
Properties Info = new Properties();
Info.load(new FileInputStream("idms.txt"));

setBKLOC(Info.getProperty("location.bkpath"));
setqPath(Info.getProperty("location.qpath"));
setexcludedfx(Info.getProperty("excluded.file.ext"));
setcheckInt(Info.getProperty("check.interval"));
setcycleInt(Info.getProperty("cycle.interval"));
setthreadCnt(Info.getProperty("no.threads"));
setkeyStore(Info.getProperty("keytore"));
setsmsServer(Info.getProperty("sms.server"));
setsmsDB(Info.getProperty("sms.database"));
setsmsDBid(Info.getProperty("sms.database.uid"));
setsmsDBpw(Info.getProperty("sms.database.pwd"));
setlogFilename(Info.getProperty("log.filename"));
setlogName(Info.getProperty("log.name"));
setlogErrname(Info.getProperty("log.errname"));

int cnt = 0;

while (cnt < 4) {
setMessage(cnt, Info.getProperty("message."+cnt));
cnt ++;
}

cnt = 1;

while (cnt<=backupCount && Info.getProperty("backup.location."+cnt)!=null) {
backupLoc.add(Info.getProperty("backup.location."+cnt));
backupRecurFlag.add(Info.getProperty("backup.location."+cnt+".recurse"));
cnt++;
}

cnt = 1;

while (Info.getProperty("sms."+cnt)!=null) {
sms.add(Info.getProperty("sms."+cnt));
cnt++;
}

cnt = 1;

while (Info.getProperty("allowed.host." + cnt)!=null) {
allowedHost.add(Info.getProperty("allowed.host." + cnt));
cnt++;
}
}
}



---------
mDir.java
---------

package com.ids;

import java.util.*;

public class mDir {
private String path;
private String name;
// All files in this directory:
private Vector files = new Vector();
// All directories in this directory:
private Vector dirs = new Vector();

public mDir(String path, String name) {
this.path = path;
this.name = name;
}

public String getName() { return name; }

public String getPath() { return path; }

public void addFile(mFile f) { files.addElement(f); }

public void addDir(mDir d) { dirs.addElement(d); }

public Vector getFiles() { return files; }

public Vector getDirs() { return dirs; }

}


----------
mFile.java
----------

package com.ids;

public class mFile {
private String path;
private String name;

public mFile(String path, String name) {
this.path = path;
this.name = name;
}

/*
* Get the name of the file
*/
public String getName() { return name; }

/*
* Get the path of the file
*/
public String getPath() { return path; }
}


----------
mList.java
----------

package com.ids;

import java.io.*;
import java.util.*;
import com.ids.*;

public class mList {
private mListNode firstNode;
private mListNode lastNode;
private mListNode current;
private String name;

private String dirname;
private mDir mdir;
private configFile config;

public void setDirname(String dirname) {
this.dirname = dirname;
}

public void build() {
File f = new File(dirname);
mdir = build(f);
}

private mDir build(File f) {
if (!f.exists()) return null;
if (!f.isDirectory()) return null;

String path = f.getPath();
String name = f.getName();
mDir mdir = new mDir(path, name);

String[] files = f.list();
HashFile.sortFileDir(path,files);
for (int i = 0; i < files.length; i++) {
File f2 = new File(path, files[i]);
if (f2.isFile()) {
//System.out.println("mlist adding - " + files[i]);
mdir.addFile(new mFile(path, files[i]));
insertAtBack(f2.getPath());
}
/*else if (f2.isDirectory()) {
File f3 = new File(path, files[i]);
mDir m = build(f3); // recursive call
if (m != null) { mdir.addDir(m); }
}*/
}
return mdir;
}

public void list() {
if (mdir == null) {
System.out.println("Not a valid directory");
return;
}
list(mdir);
}

public void list(mDir m) {
Vector md = m.getDirs();
for (int i = 0; i < md.size(); i++) {
mDir d = (mDir)md.elementAt(i);
list(d);
}

Vector mf = m.getFiles();
for (int i = 0; i < mf.size(); i++) {
mFile f = (mFile)mf.elementAt(i);
System.out.println(f.getPath() + File.separator + f.getName());
}
}

public mList (String string) {
name = string;
firstNode = lastNode = null;
}

public mList() {
this("mlist");

try {
config = new configFile();
} catch(Exception e) {
System.out.println("Error loading properties file");
return;
}
}

public synchronized void insertAtBack(Object insertItem) {
if (isEmpty())
firstNode = lastNode = new mListNode(insertItem);
else
lastNode = lastNode.nextNode = new mListNode(insertItem);
}

public synchronized boolean isEmpty() {
return firstNode == null;
}

public synchronized void print() {
if (isEmpty()) {
System.out.println ("Empty " + name);
return;
}

System.out.print("The " + name + " is: ");

current = firstNode;

while (current != null) {
System.out.print( current.data.toString()+" ");
current = current.nextNode;
}

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

public synchronized void setCurrent() {
current = firstNode;
}

public synchronized void setNext() {
if (current !=null)
current = current.nextNode;
}

public synchronized String getCurrent() {
if (current !=null)
return current.data.toString();
return null;
}

public synchronized void setList() {
/* BufferedReader in = null;
String line = null;
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream(cFile)));
} catch (IOException e) {}
try {
while ((line = in.readLine()) != null) {
setDirname(line);
build();
}
*/
int cnt = 0;
while (cnt < 5 && config.getbackupLoc(cnt) != null) {
setDirname(config.getbackupLoc(cnt));
build();
cnt++;
}
// } catch (IOException e) {}
}
}

class mListNode {
Object data;
mListNode nextNode;

mListNode(Object object) {
this(object, null);
}

mListNode(Object object, mListNode node) {
data = object;
nextNode = node;
}

Object getObject() {
return data;
}

mListNode getNext() {
return nextNode;
}
}

Go to Top of Page

Lumbago
Norsk Yak Master

3271 Posts

Posted - 2006-06-29 : 03:47:25
Do you seriously expect to get any help posting like this? People here help you for free, show some respect and make it easier to help you. Posting 10-15 lines of code will in 99% of the cases be more than enough to illustrate your problem. Nobody will do your job for you.

--
Lumbago
"Real programmers don't document, if it was hard to write it should be hard to understand"
Go to Top of Page

batmanreturn
Starting Member

3 Posts

Posted - 2006-06-29 : 04:05:51
oh okay. sorry. so if i have this lines, how do i connect to the database using mysql?

try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/+ids+?user=+idsuser+&password+=1d5u5er");
FileInputStream is = new FileInputStream(ks);
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(is, kp.toCharArray());
getKeys(alias,keyPass);
} catch (KeyStoreException e) {
System.err.println("Key store exception - " + e);
} catch (CertificateException e) {
System.err.println("Key store exception - " + e);
} catch (NoSuchAlgorithmException e) {
System.err.println("No such algorithm - " + e);
} catch (java.io.IOException e) {
System.err.println("IO exception - " + e);
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("VendorError: " + ex.getErrorCode());
}

Go to Top of Page

Lumbago
Norsk Yak Master

3271 Posts

Posted - 2006-06-29 : 04:19:58
I'm sorry but this is an MS SQL Server forum only...you might get lucky and find someone who knows mySql here but I'd recomend either the mySql forum at www.dbforums.com or the java forum at www.javaworld.com...

--
Lumbago
"Real programmers don't document, if it was hard to write it should be hard to understand"
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2006-06-29 : 05:40:35
quote:
oh okay. sorry. so if i have this lines, how do i connect to the database using mysql?
It depends on what DAL (Data Access Layer) you are using.


Peter Larsson
Helsingborg, Sweden
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2006-06-29 : 05:54:27
quote:
Originally posted by Lumbago

Do you seriously expect to get any help posting like this? People here help you for free, show some respect and make it easier to help you.
For two weeks ago, a newbie asked me to drive to work in order to get my script for encoding data. A trip of 80 miles, back and forth

I didn't drive.


Peter Larsson
Helsingborg, Sweden
Go to Top of Page
   

- Advertisement -