将des java改为triple des

时间:2015-01-06 13:24:22

标签: java encryption cryptography 3des

嗨,我有这样的代码,在DES算法中加密和解密文件。 我想将我的代码更改为三重DES加密/解密。 我的代码如下:

首先,我的方法是:

公共类DESEncrypt {

public static void encrypt(String key, InputStream is, OutputStream os) throws Exception {
    encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
}

public static void decrypt(String key, InputStream is, OutputStream os) throws Exception {
    encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
}

public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Exception {

    DESKeySpec dks = new DESKeySpec(key.getBytes());
    SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
    SecretKey desKey = skf.generateSecret(dks);
    Cipher cipher = Cipher.getInstance("DES"); 

    if (mode == Cipher.ENCRYPT_MODE) {
        cipher.init(Cipher.ENCRYPT_MODE, desKey);
        CipherInputStream cis = new CipherInputStream(is, cipher);
        makeFile(cis, os);
    } else if (mode == Cipher.DECRYPT_MODE) {
        cipher.init(Cipher.DECRYPT_MODE, desKey);
        CipherOutputStream cos = new CipherOutputStream(os, cipher);
        makeFile(is, cos);
    }
}

public static void makeFile(InputStream is, OutputStream os) throws IOException {
    byte[] bytes = new byte[64];
    int numBytes;
    while ((numBytes = is.read(bytes)) != -1) {
        os.write(bytes, 0, numBytes);
    }
    os.flush();
    os.close();
    is.close();
}

}

公共类EncryptTXT扩展了javax.swing.JFrame {

String key="Java@123##";    //This is the Key for Encryption




private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try{   
    JFileChooser fc=new JFileChooser();  
    fc.showOpenDialog(null); 
    String path=fc.getSelectedFile().getAbsolutePath(); 
    jLabel2.setText(path);
    File f=fc.getSelectedFile();
    FileInputStream fis=new FileInputStream(f);
    FileOutputStream fos=new FileOutputStream("C:/Users/user/Desktop/encrypted.txt");
    Thread.sleep(2000);

    DESEncrypt.encrypt(key, fis, fos);

    jLabel4.setText("C:/Users/user/Desktop/encrypted.txt");

1 个答案:

答案 0 :(得分:0)

  1. 3DES键长度应为16或24字节,而不是8。
  2. 按照Maarten Bodewes的建议或"DES""DESede"方法)
  3. "DESede\ECB\NoPadding"更改为.getInstance()