標籤:
1 package test; 2 3 import java.io.FileInputStream; 4 import java.io.FileOutputStream; 5 import java.io.ObjectInputStream; 6 import java.io.ObjectOutputStream; 7 import java.security.Key; 8 import java.security.KeyPair; 9 import java.security.KeyPairGenerator;10 11 import javax.crypto.Cipher;12 13 public class testcase {14 15 public static void main(String[] args) throws Exception {16 PublicEnrypt();17 privateDecrypt();18 19 }20 //加密21 public static void PublicEnrypt() throws Exception{22 // 執行個體化加密工具,使用RSA演算法23 Cipher cipher=Cipher.getInstance("RSA");24 // 執行個體化Key25 KeyPairGenerator keypairGenerator=KeyPairGenerator.getInstance("RSA");26 // 獲得一對鑰匙27 KeyPair keyPair=keypairGenerator.generateKeyPair();28 // 擷取公開金鑰29 Key publicKey=keyPair.getPublic();30 // 擷取私密金鑰31 Key privateKey=keyPair.getPrivate();32 // 用公開金鑰加密33 cipher.init(Cipher.ENCRYPT_MODE, publicKey);34 byte []result =cipher.doFinal("資料內容".getBytes("UTF-8"));35 // 將私密金鑰寫入檔案36 saveKey(privateKey,"zxx_private.key");37 // 加密後的資料存放區38 saveData(result,"public_encryt.dat"); 39 System.out.println(new String(result,"UTF-8"));40 }41 //解密42 public static void privateDecrypt() throws Exception{43 //執行個體化加密工具44 Cipher cipher=Cipher.getInstance("RSA");45 // 擷取私密金鑰46 Key privateKey=readKey("zxx_private.key");47 // 擷取加密後的資訊48 byte[] src=readData("public_encryt.dat");49 // 用私密金鑰解密50 cipher.init(Cipher.DECRYPT_MODE, privateKey);51 byte[] result=cipher.doFinal(src);52 System.out.println(new String(result,"UTF-8"));53 }54 // 儲存資料55 public static void saveData(byte[] result,String fileName) throws Exception{56 FileOutputStream fosData=new FileOutputStream(fileName);57 fosData.write(result);58 fosData.close();59 }60 // 儲存密鑰61 public static void saveKey(Key key,String fileName) throws Exception{62 FileOutputStream fosKey=new FileOutputStream(fileName);63 ObjectOutputStream oosSecretKey=new ObjectOutputStream(fosKey);64 oosSecretKey.writeObject(key);65 oosSecretKey.close();66 fosKey.close(); 67 }68 //讀取密鑰69 public static Key readKey(String fileName) throws Exception{70 FileInputStream fisKey=new FileInputStream(fileName);71 ObjectInputStream oisKey=new ObjectInputStream(fisKey);72 Key key=(Key)oisKey.readObject();73 oisKey.close();74 fisKey.close();75 return key;76 }77 // 讀取資料78 public static byte[] readData(String fileName) throws Exception{79 FileInputStream fisDat=new FileInputStream(fileName);80 byte[] src=new byte[fisDat.available()];81 int len=fisDat.read(src);82 int total=0;83 while(total<src.length){84 total+=len;85 len=fisDat.read(src, total, src.length-total);86 }87 fisDat.close();88 return src;89 }90 91 }
Java 非對稱式加密