首頁  >  文章  >  Java  >  Java 金鑰庫

Java 金鑰庫

王林
王林原創
2024-08-30 15:39:24573瀏覽

Keystore是Java中的資料庫;它允許我們以關鍵格式儲存資料; Keystore擴展自Java類java.security.KeyStore類,我們可以將keyStore寫入磁碟並從磁碟本身讀取;在Java 中使用密鑰庫的主要好處是它允許我們保護數據,因為它具有以密碼保護的形式儲存資料的功能。這些密碼就是他們的密碼,因為這種儲存功能最適合處理我們需要實作加密和解密機制的情況。

開始您的免費軟體開發課程

網頁開發、程式語言、軟體測試及其他

如何在 Java 中建立金鑰庫?

在建立Keystore之前,我們需要了解它的類型;有一些可用的金鑰機制keyStore 是公鑰(此金鑰通常包含公開的關聯憑證)、私有和公開(用於任何非對稱類型的加密)。我們可以使用Java的getInstance()方法來建立Java中的Keystore。該方法是主類別中定義的內建方法,我們已經超出了該方法。以下是在 Java 中建立預設 KeyStore 類型的範例。我之所以說它是預設值,是因為我們沒有在函數中傳遞任何參數。如果我們想要建立任何自訂 keyStore,我們可以在方法中傳遞我們所需類型的 Keystore 的參數。

KeyStore customKeyStore = KeyStore.getInstance(custom-format);

這裡我們可以傳遞custom-format = PKCS12

注意:PKCS12(這是一個公鑰,它是密碼學標準)定義了一種儲存伺服器憑證的格式。它還允許我們將私鑰儲存到單一可加密檔案。

範例

以下是使用 getInstance() 方法建立商店的範例。

代碼:

import java.io.FileInputStream;
import java.security.KeyStore;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class KeyCreate {
public static void main(String args[]) throws Exception {
//Creation of Keystore
KeyStore ks = KeyStore.getInstance("JCEKS");
System.out.println("Key Store Created");
}
}

輸出:

Java 金鑰庫

如何在 Java 中載入 KeyStore?

這裡,如果我們談論金鑰庫的載入部分,載入是金鑰庫的一個重要機制。執行此操作時我們必須小心,因為它應該僅在需要時載入。載入很重要,因為如果不載入Keystore,我們就無法使用它。也可以使用任何空資料載入金鑰庫。一般來說,我們可以從任何文件或任何其他儲存裝置載入金鑰庫。有一個方法叫load();該方法將執行載入資料的任務。我們可以將兩個屬性傳遞給 load 方法;屬性是

  • InputStream: 這是將從中讀取資料的輸入流;流可以來自任何檔案或其他來源。
  • Char []: 這部分是為了安全;在這裡,我們可以傳遞一個字串作為KeyStore密碼進行加密。

讓我們來了解載入KeyStore.load(dataStream,password)的基本流程。這裡我們可以將 inputStream 作為資料流,並使用任意字串作為密碼。正如我們所提到的,我們也可以為 KyeStore 載入空數據,這可以透過為 keyStore 的 dataStream 傳遞任何 null 值來實現,例如 KeyStore.load(null, Keystore password)。一旦我們將 null 作為資料流傳遞,它將採用 null 值並為我們建立一個空的 Keystore。關於金鑰庫的一個重要的事情是,如果我們不載入金鑰庫,它將為我們呼叫的任何方法拋出異常。為了更好的編碼實踐,在開始使用 keyStore 之前加載它非常重要。

範例

在下面的範例中,我們載入具有空值的金鑰庫。

代碼:

import java.io.FileInputStream;
import java.security.KeyStore;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class KeyLoad {
public static void main(String args[]) throws Exception {
//Creation of Keystore
KeyStore ks = KeyStore.getInstance("JCEKS");
ks.load(null);
System.out.println("Loading of an empty Keystore done");
}
}

輸出:

Java 金鑰庫

如何在Java中儲存KeyStore?

我們有很多關於在 Java 中載入和建立 KeyStore 的討論;現在讓我們專注於儲存。這裡的儲存是指我們想要儲存以供將來使用的數據,因此儲存可以在任何地方進行,可以在資料庫上,也可以在磁碟上,具體取決於我們的選擇。我們有一個名為 store 的方法,它將起到將資料儲存在 KeyStore 中的作用。我們可以將兩個屬性傳遞給 KeyStore store() 方法。下面是一個簡單的語法範例。

文法

keyStore.store(streamOfOutputData ,password);

這裡streamOfOutputData的流可以從任意路徑和檔案讀取數據,密碼就是我們儲存的資料加密的字串密碼。如果我們將來需要儲存的數據,我們可以透過再次載入它們來從儲存的位置檢索它們。

範例

代碼:

import java.io.FileInputStream;
import java.security.KeyStore;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class KeyStoreExample {
public static void main(String args[]) throws Exception {
//Creation of Keystore
KeyStore ks = KeyStore.getInstance("JCEKS");
//Loading the KeyStore object
char[] ps = "ranjan".toCharArray();
String filePath = "./cacerts";
java.io.FileInputStream streamInput = new FileInputStream(filePath);
ks.load(null);
KeyStore.ProtectionParameter pp = new KeyStore.PasswordProtection(ps);
//Here we are creating an secret object
SecretKey ms = new SecretKeySpec("anypassword".getBytes(), "DSA");
//Creating SecretKeyEntry object
KeyStore.SecretKeyEntry ske = new KeyStore.SecretKeyEntry(ms);
ks.setEntry("secretKeyAlias", ske, pp);
//Storing the object
java.io.FileOutputStream storeData = null;
storeData = new java.io.FileOutputStream("nameOfNewKey");
ks.store(storeData, ps);
System.out.println("data stored");
}
}

輸出:

Java 金鑰庫

How to Get and Set Keys?

We can use two methods called getKey and setKey to get and set the keys. These methods are part of the KeyStore in Java. The method getEntry will allow us to get the value stored. Note that we have stored the value on the key with a password, so we need to pass the alias name of the key and the password used for storing the key. Similarly, we have a method called setKeyEntry.After getting the value from the keyStore again, we can access the data with various available methods like getPrivateKey(),getcertificate(),getPrivateKey(), and getCertificateChain(). These methods can be used to get the data according to our requirements from the KeyStore.

Example

In the example below, we check if the key is available from any KeyStore.

Code:

import java.security.*;
import java.security.cert.*;
import java.util.*;
import java.io.*;
public class SetAndGetKey {
public static void main(String[] argv)
{
try {
KeyStore store = KeyStore.getInstance("JCEKS");
store.load(null);
Boolean status
= store.isKeyEntry("test");
if (status)
System.out.println("The key available");
else
System.out.println("The key is not available");
}
catch (NoSuchAlgorithmException e) {
//catch code to handle exception
}
catch (NullPointerException e) {
//catch code to handle exception
}
catch (KeyStoreException e) {
//catch code to handle exception
}
catch (FileNotFoundException e) {
//catch code to handle exception
}
catch (IOException e) {
//catch code to handle exception
}
catch (CertificateException e) {
//catch code to handle exception
}
}
}

Output:

Java 金鑰庫

Java KeyStore Methods

To perform various operations on the KeyStore, we have various methods below.

  • load(inputStream, password): It will load the keyStore data, and it needs two parameters, one as the input stream(file or any disk data) and password of string
  • store(outputStream, password): This method will be used for storing the data, and it will take two params one is output stream which from where data is going to read it could be file or disk and the second parameter is the password which will encrypt the data which we are storing.
  • getInstance(): This method is used to create a keyStore; if we pass nothing to this method, then it will create a default keyStore else, we can pass PKCS12 as the keyStore type.
  • getPrivateKey(): After getting keyStore, we can fetch private keys with this method.
  • getCertificate(): We can use this method to get the certificates.
  • getCertificateChain(): If we want to get a chain of certificates, we can use this method.

Conclusion

From this tutorial, we learned the basic concept of KeyStore in Java and about the creation, loading, and getting of various types of data from the Keystore data; we learned about the various available methods and their uses in Java for KeyStore.

以上是Java 金鑰庫的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn