package it.fmuia.apps.jling;
import it.fmuia.apps.jling.exception.SignatureNotMatchException;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SignatureException;
public class LicenseManager {
private static final int SIZE = 2048;
private LicenseProvider provider;
private EncryptionManager encriptionManager;
public LicenseManager(PublicKey publicKey, PrivateKey privateKey,
LicenseProvider provider) {
this.provider = provider;
this.encriptionManager = new EncryptionManager(publicKey, privateKey);
}
public LicenseManager(PublicKey publicKey, LicenseProvider provider) {
this(publicKey, null, provider);
}
public ILicense readLicense() throws InvalidKeyException,
NoSuchAlgorithmException, SignatureException,
SignatureNotMatchException, IOException, ClassNotFoundException {
byte[] sig;
byte[] data;
ObjectInputStream objIn = null;
ByteArrayOutputStream dataStream = null;
try {
objIn = new ObjectInputStream(new BufferedInputStream(
new ByteArrayInputStream(
this.provider.getEncryptedLicense())));
int sigLenghth = objIn.readInt();
sig = new byte[sigLenghth];
objIn.read(sig);
dataStream = new ByteArrayOutputStream();
byte[] buf = new byte[SIZE];
int len;
while ((len = objIn.read(buf)) != -1) {
dataStream.write(buf, 0, len);
}
dataStream.flush();
data = dataStream.toByteArray();
} finally {
if (objIn != null) {
objIn.close();
}
if (dataStream != null) {
dataStream.close();
}
}
if (!encriptionManager.verify(data, sig)) {
throw new SignatureNotMatchException("The signature don't match");
}
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new ByteArrayInputStream(data));
ILicense license = (ILicense) in.readObject();
return license;
} finally {
in.close();
}
}
public void writeLicense(ILicense license, File file) throws IOException,
InvalidKeyException, NoSuchAlgorithmException, SignatureException {
ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
ObjectOutputStream out = null;
ObjectOutputStream allOut = null;
try {
out = new ObjectOutputStream(dataStream);
out.writeObject(license);
byte[] data = dataStream.toByteArray();
// sign the byte array
byte[] signature = encriptionManager.sign(data);
// Write all
allOut = new ObjectOutputStream(new FileOutputStream(file));
allOut.writeInt(signature.length);
allOut.write(signature);
allOut.write(data);
allOut.flush();
} catch (IOException e) {
throw e;
} finally {
if (out != null) {
out.close();
}
if (allOut != null) {
allOut.close();
}
}
}
}