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

2014-11-24 07:34:26 · 作者: · 浏览: 6
boolean success2 = decryptedDir.mkdir();
if(!success2) {
System.out.println("EncryptZipper 创建 CHILD_DECRYPTED 文件夹的时候失败~");
return false;
}
}
}
return true;
}

/**
* 需要保留一些额外的数据,如文件的后缀格式,还有完整的密码
* 由于des加解密仅仅用到了8字节的密码,所以如果存在额外的密码,须进一步在额外数据里面得到验证,
* 验证通过的话在将加密文件还原为可用的数据文件
*/
public static byte[] combineTwoByteArray(byte[] bytesDesc, byte[] bytesData) { // 拼接两个字节数组~
int oldLen = bytesData.length;
int newLen = Description.DESC_AREA_SIZE + oldLen;
byte[] bytesDataCombined = new byte[newLen];
for(int i = 0; i < Description.DESC_AREA_SIZE; ++ i) {
bytesDataCombined[i] = bytesDesc[i];
}
for(int i = Description.DESC_AREA_SIZE; i < newLen; ++ i) {
bytesDataCombined[i] = bytesData[i - Description.DESC_AREA_SIZE];
}
return bytesDataCombined;
}
}

/**
* @author BruceYang
* 前 512 byte 用于各项属性,
* 前 512 byte 又被分成 16 份,每份 32 byte~
* 每项属性占用 32 个字节 大小的存储区域~
* 如果属性的长度超过了本身所能容纳的长度,砍断。
* 另外,每项属性以换行符 '\n' 做终止标识~
*
* 后 512 byte 用于大段文本注释(支持中文注释,base64编码解码)
* 加密文件属性描述类~
*/
class Description {
/** constructor~ */
public Description() {

}

@Override
public String toString() {
// 该方法主要用于调试~
StringBuffer sb = new StringBuffer();
sb.append("fileName=" + fileName).append('\n')
.append("fileFormat=" + fileFormat).append('\n')
.append("fileLength=" + fileLength).append('\n')
.append("password=" + password).append('\n')
.append("md5Digest=" + md5Digest).append('\n')
.append("comment=" + comment).append('\n');
return sb.toString();
}

/** 提供一个 1KB(1024Byte)的数据头,用以保存文件格式,完整密码等数据~ */
protected static final int DESC_AREA_SIZE = 1024;
protected static final int PROPERTY_LENGTH = 32;
protected static final int COMMENT_LENGTH = 512;

/** properties(暂且就弄这5个属性,描述必须为ascii)~ */
private String fileName; // offset = 0~31
private String fileFormat; // offset = 32~63
private String fileLength; // offset = 64~95
private String password; // offset = 96~127
private String md5Digest; // offset = 128~159
/** 下面这个是注释~ */
private String comment; // offset = 512~1023

protected byte[] toByteArray() {
byte[] dest = new byte[DESC_AREA_SIZE];
encodeProperty2ByteArray(fileName, dest, 0, PROPERTY_LENGTH);
encodeProperty2ByteArray(fileFormat, dest, 32, PROPERTY_LENGTH);
encodeProperty2ByteArray(fileLength, dest, 64, PROPERTY_LENGTH);
encodeProperty2ByteArray(password, dest, 96, PROPERTY_LENGTH);
encodeProperty2ByteArray(md5Digest, dest, 128, PROPERTY_LENGTH);
encodeProperty2ByteArray(comment, dest, 512, COMMENT_LENGTH);
return dest;
}

private void encodeProperty2ByteArray(String property, byte[] dest, int offset, int length) {
byte[] bytesProp = property.getBytes();
int len = bytesProp.length;
if(len >= length) {
for(int i = 0; i < length; ++ i) {
dest[offset + i] = bytesProp[i];
}
} else {