问题描述
- 关于DES算法解密的问题
-
每次运行代码生成的key值都是不一样的,所以第二次运行不进行加密部分的代码而去解密第一次生成的加密后的文件,是不可行的,这样怎么解决呢?可不可以手动给key赋值,怎么赋值?public class Locker {
Key key;
public Locker(String str) {
getKey(str);//生成密匙
}
/**
* 根据参数生成KEY
*/
public void getKey(String strKey) {
try {
KeyGenerator _generator = KeyGenerator.getInstance("DES");
_generator.init(new SecureRandom(strKey.getBytes()));
this.key = _generator.generateKey();
_generator = null;
} catch (Exception e) {
throw new RuntimeException("Error initializing SqlMap class. Cause: " + e);
}
}/** * 文件file进行加密并保存目标文件destFile中 * * @param file 要加密的文件 如mnt/sdcard/PateokeyNormal.txt * @param destFile 加密后存放的文件名 如mnt/sdcard/Pateokey.txt */ public void encrypt(String file, String destFile) throws Exception { Cipher cipher = Cipher.getInstance("DES"); // cipher.init(Cipher.ENCRYPT_MODE, getKey()); cipher.init(Cipher.ENCRYPT_MODE, this.key); InputStream is = new FileInputStream(file); OutputStream out = new FileOutputStream(destFile); CipherInputStream cis = new CipherInputStream(is, cipher); byte[] buffer = new byte[1024]; int r; while ((r = cis.read(buffer)) > 0) { out.write(buffer, 0, r); } System.out.println("KEY加密="+key); cis.close(); is.close(); out.close(); } /** * 文件采用DES算法解密文件 * * @param file 已加密的文件 如auth/Pateokey.txt * */ public String decrypt(String file) throws Exception { System.out.println("KEY解密="+key); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, this.key); InputStream is = new FileInputStream(file); String PateoMessage = ""; OutputStream out =System.out; // start ByteArrayOutputStream baos = new ByteArrayOutputStream(); CipherOutputStream cos = new CipherOutputStream(baos, cipher); // end // CipherOutputStream cos = new CipherOutputStream(out, cipher); byte[] buffer = new byte[1024]; int r; while ((r = is.read(buffer)) >= 0) { System.out.println("正在解密"); cos.write(buffer, 0, r); } cos.close(); //out.close(); is.close(); PateoMessage=baos.toString(); baos.close(); System.out.println("正在解密PateoMessage="+PateoMessage); return PateoMessage; }
}
解决方案
时间: 2024-12-06 17:16:48