【发布时间】: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