熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java生成RSA非對稱型加密的公鑰和私鑰

2022-06-13   來源: Java核心技術 

  非對稱型加密非常適合多個客戶端和服務器之間的秘密通訊客戶端使用同一個公鑰將明文加密而這個公鑰不能逆向的解密密文發送到服務器後有服務器端用私鑰解密這樣就做到了明文的加密傳送

  非對稱型加密也有它先天的缺點加密解密速度慢制約了它的發揮如果你有大量的文字需要加密傳送建議你通過非對稱型加密來把對稱型密鑰分發到客戶端及時更新對稱型密鑰

  import javaio*;

  import javasecurity*;

  import javaxcrypto*;

  import javaxcryptospec*;

  /**

  * <p>Title: RSA非對稱型加密的公鑰和私鑰</p>

  * <p>Description: </p>

  * <p>Copyright: Copyright (c) </p>

  * <p>Company: </p>

  * @author not attributable

  * @version

  */

  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 指定密匙長度(取值范圍

  * @throws NoSuchAlgorithmException 異常

  */

  public KeyRSA(int in String address) throws NoSuchAlgorithmExceptionFileNotFoundException IOException

  {

  kpg = KeyPairGeneratorgetInstance(RSA); //創建密匙對生成器

  kpginitialize(in); //指定密匙長度(取值范圍

  kp = kpggenKeyPair(); //生成密匙對其中包含著一個公匙和一個私匙的信息

  public_key = kpgetPublic(); //獲得公匙

  private_key = kpgetPrivate(); //獲得私匙

  //保存公匙

  public_file_out = new FileOutputStream(address + /public_keydat);

  public_object_out = new ObjectOutputStream(public_file_out);

  public_object_outwriteObject(public_key);

  //保存私匙

  private_file_out = new FileOutputStream(address + /private_keydat);

  private_object_out = new ObjectOutputStream(private_file_out);

  private_object_outwriteObject(private_key);

  }

  public static void main(String[] args) {

  try {

  Systemoutprintln(私匙和公匙保存到C盤下的文件中);

  new KeyRSA( c:/);

  }

  catch (IOException ex) {

  }

  catch (NoSuchAlgorithmException ex) {

  }

  }

  }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26592.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.