import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Administrator
*/
public class GenKey {
public static void main(String[] args){//產生密鑰
//將密鑰儲存在檔案中
try {
KeyGenerator keyGen = KeyGenerator.getInstance("DESede");
//初始化金鑰產生器
keyGen.init(168);
//產生密鑰
SecretKey key = keyGen.generateKey(); //以二進位檔案流形式儲存
//將密鑰儲存在檔案中
FileOutputStream f = new FileOutputStream("key3.dat");
ObjectOutputStream b = new ObjectOutputStream(f);
b.writeObject(key);
f.close();
b.close();
} catch (Exception ex) {
Logger.getLogger(GenKey.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cipherinputstream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.security.Key;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
/**
*
* @author Administrator
*/
public class EncryptAndDecrypt {
public static void main(String[] args){
//要用作加密或解密的檔案名稱
String dataFileName=args[0];
//是區分是加密還是解密,加密為encrypt,解密為decrypt
String opMode=args[1];
//密鑰存放的檔案名稱
String keyFileName="key.dat";
try {
//產生密鑰
FileInputStream keyFIS = new FileInputStream(keyFileName);
ObjectInputStream OIS=new ObjectInputStream(keyFIS);
Key key=(Key)OIS.readObject();
//建立並初始化密碼器
Cipher cp=Cipher.getInstance("DESede");
if(opMode.equalsIgnoreCase("encrypt")){
cp.init(Cipher.ENCRYPT_MODE, key);
}
else if(opMode.equalsIgnoreCase("decrypt")){
cp.init(Cipher.DECRYPT_MODE, key);
}
else return;
//建立CipherInputStream對象
FileInputStream dataFIS=new FileInputStream(dataFileName);
CipherInputStream CIS=new CipherInputStream(dataFIS,cp);
//如果是加密操作
if(opMode.equalsIgnoreCase("encrypt")){
//建立檔案輸出資料流
FileOutputStream FOS=new FileOutputStream("mi.txt");
int b=0;
System.out.print("加密後的密文是:");
while((b=CIS.read())!=-1){
System.out.print((char)b);
FOS.write((byte)b);
}
System.out.println("/n密文已經寫到檔案裡。");
}
else{//如果是解密操作
int b=0;
FileOutputStream FOS=new FileOutputStream("jiemi.txt");
System.out.print("解密後的明文是:");
while((b=CIS.read())!=-1){
FOS.write(b);//寫入檔案中
}
}
} catch (Exception ex) {
Logger.getLogger(EncryptAndDecrypt.class.getName()).log(Level.SEVERE, null, ex);
}
}
}