devin_lxs 2015-11-18 10:25 采纳率: 33.3%
浏览 1778

关于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;
  } 

}

  • 写回答

1条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决