【问题标题】:change des java to triple des将des java更改为三重des
【发布时间】:2015-01-06 13:24:21
【问题描述】:

您好,我有这样的代码,可以在 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");

【问题讨论】:

  • 为什么?替换 DES 已经是一项重大更改,因此如果您这样做,请切换到 AES-GCM 之类的现代技术。
  • 我们不是来做你的工作的。你试过什么?
  • Maarten 我尝试用 DESede 替换 DES,但它不起作用。
  • 您是否尝试生成 24 字节的 "DESede" 键?请注意,密钥是二进制的,而不是 Strings。

标签: java encryption cryptography 3des


【解决方案1】:
  1. 3DES 密钥的长度应为 16 或 24 个字节,而不是 8 个。
  2. 按照 Maarten Bodewes 或 "DESede\ECB\NoPadding" 的建议将 "DES" 更改为 "DESede"(在 .getInstance() 方法中)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 2011-07-30
    相关资源
    最近更新 更多