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

2014-11-24 07:34:26 · 作者: · 浏览: 1
desc.setFileFormat(suffix);
desc.setFileLength(String.valueOf(f.length()));
desc.setPassword(PWD);
desc.setMd5Digest("1231231231231234"); // md5 摘要的长度为 128 bit, 16 byte~

// 下面是一个长度超过512字节的字符串(86 * 11 = 946),测试一下长度超过规定长度自动被砍断的功能
desc.setComment("My name is Yang3wei, i love java the most!!My name is Yang3wei, i love java the most!!" +
"My name is Yang3wei, i love java the most!!My name is Yang3wei, i love java the most!!" +
"My name is Yang3wei, i love java the most!!My name is Yang3wei, i love java the most!!" +
"My name is Yang3wei, i love java the most!!My name is Yang3wei, i love java the most!!" +
"My name is Yang3wei, i love java the most!!My name is Yang3wei, i love java the most!!" +
"My name is Yang3wei, i love java the most!!My name is Yang3wei, i love java the most!!" +
"My name is Yang3wei, i love java the most!!My name is Yang3wei, i love java the most!!" +
"My name is Yang3wei, i love java the most!!My name is Yang3wei, i love java the most!!" +
"My name is Yang3wei, i love java the most!!My name is Yang3wei, i love java the most!!" +
"My name is Yang3wei, i love java the most!!My name is Yang3wei, i love java the most!!" +
"My name is Yang3wei, i love java the most!!My name is Yang3wei, i love java the most!!");
return desc;
}


/**
* 从指定字符串生成密钥,密钥所需的字节数组长度为8位 不足8位时后面补0,超出8位只取前8位
* @param arrBTmp 构成该字符串的字节数组
* @return 生成的密钥
* @throws Exception
*/
private static byte[] getBytesKey(byte[] bytesKeyRaw) throws Exception {
// 创建一个空的8位字节数组(默认值为0)
byte[] bytesKey = new byte[8];
// 将原始字节数组转换为8位
for (int i = 0; i < bytesKeyRaw.length && i < bytesKey.length; i++) {
bytesKey[i] = bytesKeyRaw[i];
}
return bytesKey;
}


/**
* 用 DES方法加密(或解密)输入的字节。bytKey 须为 8 字节长,是加密(或解密)的密码~
*/
private static byte[] doFinalWithDES(byte[] bytesData, byte[] bytesKey, int desMode) throws Exception {
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
DESKeySpec desKS = new DESKeySpec(bytesKey);
SecretKey sk = skf.generateSecret(desKS);

Cipher cip = Cipher.getInstance("DES");
cip.init(desMode, sk);
return cip.doFinal(bytesData);
}

/**
* 准备工作,建立几个主要目录(如果他们不存在)~
* @return
*/
private static boolean prepare() {
// 1。检查 BASE_PATH 文件夹是否存在?如果不存在,创建为文件夹~
File baseDir = new File("/Users/user/MyData/MyPersonal");
if(!baseDir.exists()) {
boolean success = baseDir.mkdir();
if(!success) {
System.out.println("EncryptZipper 创建 BASE_PATH 文件夹的时候失败~");
return false;
}
File encryptedDir = new File(ENCRYPTED_DIR);
if(!encryptedDir.exists()) {
boolean success1 = encryptedDir.mkdir();
if(!success1) {
System.out.println("EncryptZipper 创建 CHILD_ENCRYPTED 文件夹的时候失败~");
return false;
}
}
File decryptedDir = new File(DECRYPTED_DIR);
if(!decryptedDir.exists()) {