2019年3月15日 星期五

[JAVA] 實作:用公鑰將字串加密後存入檔案,再從檔案讀取並用私鑰解密 (part 2/2) -- RSA 非對稱式加密

請先參考part1後再來此篇,

此篇是將前篇產出的password.txt及private.key檔都複製移動到另一隻程式的資料夾,
再用新的程式去讀取它,並解出原本的密碼然後放在string中,
即可隨個人需求搭配其它程式碼去使用。




此部份使用了兩個class,
主要的class (blog123.java):




package blog123;


public class blog123 {

 public static void main(String[] args) {
  // TODO Auto-generated method stub

  String pWord=null;
  try {
   pWord = getPass.readFileGetPass( "src\\" );
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  System.out.println("pWord = " + pWord);
  
  
 }

}





另一個的class(getPass.java):




package blog123;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

import javax.crypto.Cipher;

public class getPass {

 public static String readFileGetPass(String path) throws Exception {
  // TODO Auto-generated method stub
  
  File passwordFile = new File (path);
    
    
    FileInputStream fileInputStream = new FileInputStream( path + "password.txt" );
    DataInputStream  dis = new DataInputStream(fileInputStream);
          
          // count the available bytes form the input stream
          int count = dis.available();
          
          // create buffer
          byte[] bs = new byte[count];
          
          // read data into buffer
          dis.read(bs);
          dis.close();
       
       // 讀取金鑰  Load the keys
       KeyPair loadedKeyPair = loadKeyPair(path, "RSA"); // Load the keys from files
    
    
    byte [] passwordDecrypt= decrypt (bs,loadedKeyPair.getPrivate() );
    String ReadPasswordFile = new String (passwordDecrypt);
    System.out.println("\n" + "密碼從檔案讀取後" + "\n" + "解密取得之字串= " +  ReadPasswordFile );
  
  return ReadPasswordFile;
 }

  //私鑰解密
  public static byte[] decrypt(byte[] content, PrivateKey privateKey) throws Exception{
  Cipher cipher=Cipher.getInstance("RSA");
  cipher.init(Cipher.DECRYPT_MODE, privateKey);
  return cipher.doFinal(content);
  }
  
  //從path讀取金鑰檔
  public static KeyPair loadKeyPair(String path, String algorithm)
       throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    
     // Initiate the factory with specified algorithm.
     KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
      
     
      
     PublicKey publicKey = null;
     
      
     // Read private key from file.
     File fileForPrivateKey = Paths.get(path, "private.key").toFile();
     //log.trace("Private key will be loaded from '{}'.", fileForPrivateKey);
      
     PrivateKey privateKey = null;
     try (FileInputStream fis = new FileInputStream(fileForPrivateKey)) {
       byte[] loadedBytes = new byte[(int) fileForPrivateKey.length()];
       fis.read(loadedBytes);
        
       PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(loadedBytes);
       privateKey = keyFactory.generatePrivate(privateKeySpec);
     }
    
     return new KeyPair(publicKey, privateKey);
   }
 

}


沒有留言: