Java中 DES加密算法

2025-04-03 13:13:57
推荐回答(1个)
回答1:

三个文件:
一:skey_DES.java
//对称秘钥生成及对象化保存
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class Skey_DES
{
public static void main(String args[])throws Exception
{
KeyGenerator kg=KeyGenerator.getInstance("DESede");
kg.init(168);
SecretKey k=kg.generateKey();
FileOutputStream f=new FileOutputStream("key1.txt");
ObjectOutputStream b= new ObjectOutputStream(f);
b.writeObject(k);
}
};

二:SEnc.java
//对称秘钥加密,使用字节码
import java.io.*;
import java.security.*;
import javax.crypto.*;

public class SEnc
{
public static void main(String args[]) throws Exception
{
String s="Hello123Hello123Hello123Hello123";

FileInputStream f=new FileInputStream("key1.txt");
ObjectInputStream b=new ObjectInputStream(f);
Key k=(Key)b.readObject();
Cipher cp=Cipher.getInstance("DESede");
cp.init(Cipher.ENCRYPT_MODE,k);

byte ptext[]=s.getBytes("UTF8");
for(int i=0;i {
System.out.print(ptext[i]+",");
}
System.out.println("");
byte ctext[]=cp.doFinal(ptext);
for(int i=0;i {
System.out.print(ctext[i]+",");
}
FileOutputStream f2=new FileOutputStream("SEnc.txt");
f2.write(ctext);
}
};
三:SDec.java
//使用对称秘钥解密
import java.io.*;
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class SDec
{
public static void main(String args[])throws Exception
{
FileInputStream f=new FileInputStream("SEnc.txt");
int num=f.available();
byte[] ctext=new byte[num];
f.read(ctext);

FileInputStream f2=new FileInputStream("key1.txt");
ObjectInputStream b=new ObjectInputStream(f2);
Key k=(Key)b.readObject();
Cipher cp=Cipher.getInstance("DESede");
cp.init(Cipher.DECRYPT_MODE,k);

byte[] ptext=cp.doFinal(ctext);
String p=new String(ptext,"UTF8");
System.out.println(p);
}
};