Java產生非對稱型加密公開金鑰和私密金鑰的方法_java

來源:互聯網
上載者:User

本文執行個體講述了Java產生非對稱型加密公開金鑰和私密金鑰的方法。分享給大家供大家參考。具體如下:

非對稱型加密非常適合多個用戶端和伺服器之間的秘密通訊,用戶端使用同一個公開金鑰將明文加密,而這個公開金鑰不能逆向的解密,密文發送到伺服器後有伺服器端用私密金鑰解密,這樣就做到了明文的加密傳送。
非對稱型加密也有它先天的缺點,加密、解密速度慢制約了它的發揮,如果你有大量的文字需要加密傳送,建議你通過非對稱型加密來把對稱型‘密鑰'分發到用戶端,及時更新對稱型‘密鑰'。

KeyRSA.java如下:

import java.io.*;import java.security.*;import javax.crypto.*;import javax.crypto.spec.*;/** * RSA非對稱型加密的公開金鑰和私密金鑰 */public class KeyRSA { private KeyPairGenerator kpg = null; private KeyPair kp = null; private PublicKey public_key = null; private PrivateKey private_key = null; private FileOutputStream public_file_out = null; private ObjectOutputStream public_object_out = null; private FileOutputStream private_file_out = null; private ObjectOutputStream private_object_out = null; /**  * 建構函式  * @param in 指定密匙長度(取值範圍:512~2048)  * @throws NoSuchAlgorithmException 異常  */ public KeyRSA(int in, String address) throws NoSuchAlgorithmException,   FileNotFoundException, IOException {  kpg = KeyPairGenerator.getInstance("RSA"); //建立‘密匙對'產生器  kpg.initialize(in); //指定密匙長度(取值範圍:512~2048)  kp = kpg.genKeyPair(); //產生‘密匙對',其中包含著一個公匙和一個私匙的資訊  public_key = kp.getPublic(); //獲得公匙  private_key = kp.getPrivate(); //獲得私匙  //儲存公匙  public_file_out = new FileOutputStream(address + "/public_key.dat");  public_object_out = new ObjectOutputStream(public_file_out);  public_object_out.writeObject(public_key);  //儲存私匙  private_file_out = new FileOutputStream(address + "/private_key.dat");  private_object_out = new ObjectOutputStream(private_file_out);  private_object_out.writeObject(private_key); } public static void main(String[] args) {  try {   new KeyRSA(1024, "c:/key_rsa");  }  catch (IOException ex) {  }  catch (NoSuchAlgorithmException ex) {  } }}

希望本文所述對大家的java程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.