读书那会儿,觉得密码学是个很难懂的学科,工作以后,加密和解密也基本没什么接触。不巧的是,眼下正好要有一项工作,需要对加密文件进行解密,具体的步骤如下:
- 步骤1:对设备编号进行MD5加密,生成解密密钥;
- 步骤2:对.cepub文件使用解密密钥进行DES解密,并生成文件到一个临时缓冲区。
书到用时方恨少,一番查阅 API 和 Google,期间找到两篇不错的资料 Java 加密技术(一)和 Java 加密技术(二),解了燃眉之急,顺便提一下,这两篇资料的作者也是《Java 加密和解密的艺术》一书的作者。
以下是我实现上述两个步骤的代码片段,估计下次再遇到时难免有遗忘,干脆粘贴出来,既扩充一下版面内容,又可以日后回顾。
/**
* 对加密文件进行解密
*
* @param sourceFile 加密文件
* @param key 密钥
* @return 解密后文件的路径
*/
private String getDecryptedFile(String sourceFile, Key key) {
String foldPath = "/home/poemcode/";
int beginIndex = sourceFile.lastIndexOf(File.separator);
int endIndex = sourceFile.lastIndexOf(".");
String dest = foldPath + sourceFile.substring(beginIndex, endIndex) + ".epub";
Cipher cipher = null;
try {
cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
InputStream is = null;
OutputStream out = null;
CipherOutputStream cos = null;
try {
is = new FileInputStream(sourceFile);
out = new FileOutputStream(dest);
cos = new CipherOutputStream(out, cipher);
byte[] buffer = new byte[1024];
int r;
while ((r = is.read(buffer)) >= 0) {
cos.write(buffer, 0, r);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (cos != null) {
try {
cos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (cos != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (cos != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return dest;
}
/**
* 返回DES解码的密钥
*
* @param serialNumber
* 机器序列号
* @return 密钥
*/
private Key getKey(String serialNumber) {
Key secretKey = null;
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(serialNumber.getBytes());
DESKeySpec dks = new DESKeySpec(md5.digest());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
secretKey = keyFactory.generateSecret(dks);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
return secretKey;
}