Torrent.cheers();自定义密码长度的一个文件加密类(四)

2014-11-24 07:34:26 · 作者: · 浏览: 2

}
} catch (Exception e) {
e.printStackTrace();
}
}
BY.byLog("已将 " + pathList.size() + " 个文件加密(解密)到目标文件!!");
return true;
}


/**
* 对文件的数据字节数组进行 8 个字符密钥的 DES 加密~
* @param f
* @return
* @throws Exception
*/
public static boolean encryptFile(File f) throws Exception {
byte[] bytesData = IOUtils.toByteArray(new FileInputStream(f));
byte[] bytesDesc = getFileDescription(f).toByteArray();

/** 将文件描述字节数组与文件数据字节数组拼接起来~ */
byte[] bytesDataCombined = combineTwoByteArray(bytesDesc, bytesData);

/** 是英文混数字的,不用管编码什么的(发现我还是有点儿不明白)~ */
byte[] bytesKey = getBytesKey(PWD.getBytes());

byte[] bytesDataEncrypted = doFinalWithDES(bytesDataCombined, bytesKey, Cipher.ENCRYPT_MODE);

String prefix = f.getName().substring(0, f.getName().lastIndexOf('.'));
File encryptedFile = new File(ENCRYPTED_DIR + File.separator + prefix + ".des");

IOUtils.write(bytesDataEncrypted, new FileOutputStream(encryptedFile));
return true;
}

/**
* 解密被加密过后的文件~
* @param f
* @return
* @throws Exception
*/
public static boolean decryptFile(File f) throws Exception {
byte[] bytesData = IOUtils.toByteArray(new FileInputStream(f));
byte[] bytesKey = getBytesKey(PWD.getBytes());

byte[] bytesDataDecrypted = doFinalWithDES(bytesData, bytesKey, Cipher.DECRYPT_MODE);
int len = bytesDataDecrypted.length;
int descLen = Description.DESC_AREA_SIZE;

Description desc = Description.descriptionFromBytes(bytesDataDecrypted);
if(!desc.getPassword().equals(PWD)) {
System.err.println("密码不正确,退出~");
/**
* 实际上走到这里已经很玄乎了,能走到这里说明输入密码的前 8 位和正确密码是能够相匹配的,
* 否则是无法突破 DES 加密这一关的,但是我在 desc 对象里面仍然保留了最后一道防线。
* 虽然 DES 加密仅用到了密码的前 8 位,但是如果 8 位以后的字符和 desc 里面保留的密码对不上,
* 也不会让套密码的人得到正确解密后的数据文件~
*/
return false;
}

System.out.println(desc.toString());

File decryptedFile = new File(DECRYPTED_DIR + File.separator
+ desc.getFileName() + '.' + desc.getFileFormat());

FileOutputStream fos = new FileOutputStream(decryptedFile);
fos.write(bytesDataDecrypted, descLen, len - descLen);
fos.flush();
fos.close();
return true;
}

// String.getBytes():
// Encodes this String into a sequence of bytes using
// the platform's default charset, storing the result into a new byte array.

/**
* 获取文件的描述对象 www.2cto.com
* (描述对象中包含了文件的一部分属性值:
* 文件名,文件后缀名,文件长度, 加密文件所用密码,数字摘要以及对压缩文件的注释)~
* @param f
* @return
*/
public static Description getFileDescription(File f) {
String fName = f.getName();
String prefix = fName.substring(0, fName.lastIndexOf('.'));
String suffix = fName.substring(fName.lastIndexOf('.') + 1);

Description desc = new Description();
desc.setFileName(prefix);