Coverage details for base.jdbs.BackupArtifactAssembler

LineHitsSource
1 /*******************************************************************************
2  *InternetCafe is a software solution that helps the management of Cybercafes
3  * according with the ITALIAN DECREE LAW ON ANTI-TERROR MEASURES, 27 JULY 2005.
4  * Copyright (C) 2006 Guido Angelo Ingenito
5  
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *******************************************************************************/
20 package base.jdbs;
21  
22 import java.io.File;
23 import java.io.FileWriter;
24 import java.io.IOException;
25 import java.io.PrintStream;
26  
27 import javax.xml.parsers.DocumentBuilderFactory;
28 import javax.xml.transform.Transformer;
29 import javax.xml.transform.TransformerFactory;
30 import javax.xml.transform.dom.DOMSource;
31 import javax.xml.transform.stream.StreamResult;
32  
33 import org.apache.log4j.Logger;
34 import org.w3c.dom.Document;
35  
36 import base.jdbs.cryptography.asymmetric.KeyPair;
37 import base.jdbs.cryptography.asymmetric.RSAAsymmetricCipher;
38 import base.jdbs.cryptography.symmetric.DESSymmetricCipher;
39 import base.jdbs.cryptography.symmetric.SymmetricKey;
40 import base.util.FileUtil;
41 import base.util.ZipUtil;
42  
43 /**
44  * This class provided methods and utils to assembly a backup.
45  * @author Guido Angelo Ingenito
46  */
470public class BackupArtifactAssembler {
48     
49     public static final String ENCRYPTION_DIRECTORY_NAME = "enc";
50     public static final String DECRYPTION_DIRECTORY_NAME = "dec";
51  
520    private static final transient Logger logger = Logger.getLogger(BackupArtifactAssembler.class.getName());
53     
540    /**
55      * This method builds a new signed backup artifact placing it into a temp directory.
56      * The backup building process is fully described in the JDBS analysis and it consists of some phases:
57      * Phase 1: backup files encryption (only in the case of PRIVATE content).
58      * Phase 2: backup info file creation.
59      * Phase 3: backup compression.
60      * Phase 4: backup CRC32 Checksum, MD5 Digest and X509 certificate file creation.
61      * Phase 5: backup asymmetric signature ( the signature is placed on the MD5 Digest file and a new signed file is created ).
62      * @param symmetricKey The symmetric key to use in the encryption process.
63      * @param keyPair The asymmetric key pair to be used during the signing phase.
64      * @param backup The input backup from which the backup artifact must be created.
65      * @return The directory where the backup has been created and that contains the Compressed and Encrypted Backup Artifact and
66      * some info files. This outputted directory reference should be moved to the local JDBS users'repository.
67      * @throws IOException If something wrong happens with the filesystem.
68      */
69     public static File buildNewBackupArtifact(File repositoryDirectory, SymmetricKey symmetricKey, KeyPair keyPair, Backup backup) throws IOException{
70         
710        final String backupArtifactName = backup.getGuId()+"-"+backup.getName();
72         //This is the backup directory under the local Repository
730        final File backupDirectory = new File(repositoryDirectory,backupArtifactName);
740        backupDirectory.mkdir();
750        logger.debug("Backup Directory on local Repository: "+ backupDirectory);
760        
770        final File encryptionDir = new File(backupDirectory,ENCRYPTION_DIRECTORY_NAME);
780        final File decryptionDir = new File(backupDirectory,DECRYPTION_DIRECTORY_NAME);
790        
800        logger.debug("Backup Encryption Directory: "+ encryptionDir);
810        encryptionDir.mkdir();
820        logger.debug("Backup Decryption Directory: "+ decryptionDir);
830        decryptionDir.mkdir();
840        
850        //Each backups' file must be encrypted preserving the directory structure on the filesystem...
860        logger.debug("Backup's security level: "+backup.getSecurityLevel());
870        if(backup.getSecurityLevel().equals(SecurityLevel.PRIVATE)){
880            logger.debug("Symmetric encryption with key: "+symmetricKey.getValue()+"...");
890            
900            DESSymmetricCipher symmetricCipher = new DESSymmetricCipher(symmetricKey);
91             
92             //Here starts the file encryption
930            for(int i=0;i<backup.getFileDescriptor().length;i++){
940                File encFile = new File(encryptionDir, backup.getFileDescriptor()[i].getFile().getAbsolutePath());
950                encFile.getParentFile().mkdirs();
960                encFile.createNewFile();
970                symmetricCipher.encrypt(backup.getFileDescriptor()[i].getFile(),encFile);
98             }
990            
1000            
1010        }else{
1020            logger.debug("Moving backup's files under the decryption folder, backup has PUBLIC content...");
1030            //Here starts the file copy
1040            for(int i=0;i<backup.getFileDescriptor().length;i++){
1050                File decFile = new File(decryptionDir, backup.getFileDescriptor()[i].getFile().getAbsolutePath());
1060                decFile.getParentFile().mkdirs();
1070                decFile.createNewFile();
1080                FileUtil.copyFile(backup.getFileDescriptor()[i].getFile(),decFile);
109             }
110             
1110        }
1120        
1130        final File compressedFile;
1140        if(backup.getSecurityLevel().equals(SecurityLevel.PRIVATE)){
1150            logger.debug("Backup has PRIVATE content, compressing the encryption directory...");
1160            compressedFile = new File(backupDirectory,backupArtifactName+JDBSConstant.DOTTED_ZIP_EXTENSION);
1170            compressedFile.createNewFile();
1180            ZipUtil.zipDirectory(encryptionDir,compressedFile);
1190        }
1200        else{
1210            logger.debug("Backup has PUBLIC content, compressing the decryption directory...");
1220            compressedFile = new File(backupDirectory,backupArtifactName+JDBSConstant.DOTTED_ZIP_EXTENSION);
1230            compressedFile.createNewFile();
1240            ZipUtil.zipDirectory(decryptionDir,compressedFile);
125             
1260        }
1270        
1280        //Here must be stored in xml the informations relative to the backup content...
1290        logger.debug("Building the backup's xml info file...");
1300        final File infoFile = new File(backupDirectory,JDBSConstant.XML_INFO_FILE_NAME);
1310        writeBackupXmlInfoFile(backup, infoFile);
132         
1330        //Making a CRC32 for the compressed backup artifact...
1340        logger.debug("Writing backup's CRC32 Checksum...");
1350        final File crc32File = new File(backupDirectory,JDBSConstant.CRC32_FILE_NAME);
1360        writeBackupCRC32Checksum(crc32File, compressedFile);
137         
138         //Making an MD5 digest for the compressed backup artifact, this will be signed with the users'private key...
1390        logger.debug("Writing backup's MD5 Digest...");
1400        final File md5File = new File(backupDirectory,JDBSConstant.MD5_FILE_NAME);
1410        writeBackupMD5Digest(md5File, compressedFile);
142         
143         //In each case, PRIVATE or PUBLIC content the backup MD5 must be signed with the privateKey to check integrity and security...
1440        logger.debug("Signing the backup artifact's MD5 digest...");
1450        RSAAsymmetricCipher asymmetricCipher = new RSAAsymmetricCipher();
1460        final File signedDigest = new File(md5File+JDBSConstant.DOTTED_SIGNED_EXTENSION);
1470        if(keyPair == null)throw new IllegalArgumentException("AFFF1");
1480        if(keyPair.getPrivateKey() == null)throw new IllegalArgumentException("AFFF2");
1490        
1500        asymmetricCipher.sign(md5File, signedDigest,keyPair.getPrivateKey() );
151         
1520        //The keyPair associated certificate must be stored to the output directory...
1530        logger.debug("Writing the X509Certificate...");
1540        File certificateFile = new File(backupDirectory,JDBSConstant.CERTIFICATE_FILE_NAME);
1550        writeX509Certificate(keyPair.getCertificate(), certificateFile);
1560        
1570        logger.debug("Encryption Directory Deletion Result: " + FileUtil.deleteDirectory(encryptionDir));
1580        logger.debug("Decryption Directory Deletion Result: " + FileUtil.deleteDirectory(decryptionDir));
1590        
1600        logger.debug("Backup artifact successfully created...");
1610        return backupDirectory;
1620    }
1630    
1640    /**
1650     * This method writes to a file the info associated to a backup, in xml format.
1660     * @param backup The backup whose info must be stored to the output file.
1670     * @param outputInfo The outputFile where the info will be stored.
1680     */
169     protected static void writeBackupXmlInfoFile(Backup backup, File outputInfo){
1700        try {
1710            Document backupInfoDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
1720            backupInfoDocument.appendChild(backup.toXml(backupInfoDocument));
1730            Transformer transformer = TransformerFactory.newInstance().newTransformer();
1740            DOMSource source = new DOMSource(backupInfoDocument);
1750            StreamResult streamResult = new StreamResult(new PrintStream(outputInfo));
1760            transformer.transform(source, streamResult);
1770        } catch (Exception ex) {
1780            logger.error(ex.getMessage());
1790            ex.printStackTrace();
1800        }
1810    }
1820    
1830    /**
1840     * This method writes a CRC32 Checksum to a file.
1850     * @param crc32Output The CRC32 Checksum file to be written.
1860     * @param compressedBackup The Compressed Backup Artifact from which the CRC32 must be computed.
1870     */
1880    protected static void writeBackupCRC32Checksum(File crc32Output, File compressedBackup){
1890        FileWriter fileWriter;
190         try {
1910            fileWriter = new FileWriter(crc32Output);
1920            String backupCRC32 = FileUtil.createCRC32Checksum(compressedBackup).toString();
1930            logger.debug("File: "+compressedBackup + " CRC32: "+backupCRC32);
1940            fileWriter.write(backupCRC32);
1950            fileWriter.close();
1960        } catch (IOException ex) {
1970            logger.error(ex.getMessage());
1980            ex.printStackTrace();
1990        }
2000    }
2010    
2020    /**
2030     * This method writes a MD5 Digest to a file.
2040     * @param MD5DigestOutput The MD5 Digest file to be written.
2050     * @param compressedBackup The Compressed Backup Artifact from which the CRC32 must be computed.
2060     */
2070    protected static void writeBackupMD5Digest(File MD5DigestOutput, File compressedBackup){
2080        FileWriter fileWriter;
209         try {
2100            fileWriter = new FileWriter(MD5DigestOutput);
2110            String backupMD5Digest = FileUtil.createMD5Digest(compressedBackup);
2120            logger.debug("File: "+compressedBackup + " MD5: "+backupMD5Digest);
2130            fileWriter.write(backupMD5Digest);
2140            fileWriter.close();
2150        } catch (IOException ex) {
2160            logger.error(ex.getMessage());
2170            ex.printStackTrace();
2180        }
2190    }
2200    
2210 
2220    /**
2230     * This method writes to a file an X509Certificate.
2240     * @param certificate The certificate that must be saved.
2250     * @param certificateFile The output file where the certificate must be stored.
2260     */
2270    protected static void writeX509Certificate(java.security.cert.X509Certificate certificate, File certificateFile){
228         FileWriter fileWriter;
229         try {
2300            fileWriter = new FileWriter(certificateFile);
2310            logger.debug("Certificate: \n"+ certificate + "\nSaved in file: "+certificateFile);
2320            fileWriter.write(certificate.toString());
2330            fileWriter.close();
2340        } catch (IOException ex) {
2350            logger.error(ex.getMessage());
2360            ex.printStackTrace();
2370        }
2380    }
2390}

this report was generated by version 1.0.5 of jcoverage.
visit www.jcoverage.com for updates.

copyright © 2003, jcoverage ltd. all rights reserved.
Java is a trademark of Sun Microsystems, Inc. in the United States and other countries.